InterviewSolution
| 1. |
What is the role of final variables in C#? |
|
Answer» There are no final variables in C# as the keyword final is available in Java and not in C#. The KEYWORDS readonly and sealed in C# have the same IMPLEMENTATION as final in Java. Details about readonly and sealed in C# are given as follows:
In a field declaration, the readonly keyword specifies that assignment for a field can only occur with declaration or using the constructor of the same class. A program that demonstrates the readonly keyword is given as follows: using System; class Student { readonly INT rollNo; public Student(int rno) { rollNo = rno; } public int getRollNumber() { // rollNo = 7; return this.rollNo; } } public class Demo { public static void Main() { Student s = new Student(105); Console.WriteLine("Roll Number: " + s.getRollNumber()); } }The output of the above program is as follows: Roll Number: 105In the above program, the variable rollNo is readonly and so it cannot be assigned a value in method getRollNumber(). So if the comments are removed, an error would be obtained.
The sealed keyword is used in classes to restrict inheritance. So sealed classes are those classes that cannot be extended and no class can be derived from them. A program that demonstrates the sealed keyword in C# is given as follows: using System; sealed class A { int a = 5; public int returna() { return a; } } class Demo { static void Main(string[] args) { A OBJ = new A(); Console.WriteLine("a = " + obj.returna()); } }The output of the above program is as follows: a = 5In the above program, the class A is a sealed class. This means that it cannot be inherited and an error will be generated if any class is derived from the class A. |
|