C# Interview Question and Answers with Example - Part 7


Below is top 100 C# interview question and answers with examples for freshers and intermediate developers.

What are instance fields in C#?

Instance fields are specific to an instance of a type. If you have a class T, with an instance field F, you can create two objects of type T, and modify the value of F in each object without affecting the value in the other object.

What is a static field?

A static field belongs to the class itself, and is shared among all instances of that class. Changes made from instance A will be visible immediately to instances B and C if they access the field.

Will the following code compile?

using System;
class Area
{
public static double PI = 3.14;
}
class MainClass
{
public static void Main()
{
Area A = new Area();
Console.WriteLine(A.PI);
}
}

No, a compile time error will be generated stating "Static member 'Area.PI' cannot be accessed with an instance reference; qualify it with a type name instead". This is because PI is a static field. Static fields can only be accessed using the name of the class and not the instance of the class. The above sample program is rewritten as shown below.

using System;
class Area
{
public static double PI = 3.14;
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Area.PI);
}
}

Can you declare a field readonly?

Yes, a field can be declared readonly. A read-only field can only be assigned a value during initialization or in a constructor. An example is shown below.

using System;
class Area
{
public readonly double PI = 3.14;
}
class MainClass
{
public static void Main()
{
Area A = new Area();
Console.WriteLine(A.PI);
}
}

Will the following code compile?

using System;
class Area
{
public readonly double PI = 3.14;
}
class MainClass
{
public static void Main()
{
Area A = new Area();
A.PI = 3.15;
Console.WriteLine(A.PI);
}
}

No, PI is readonly. You can only read the value of PI in the Main() method. You cannot assign any value to PI.

What is wrong with the sample program below?

using System;
class Area
{
public const double PI = 3.14;
static Area()
{
Area.PI = 3.15;
}
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Area.PI);
}
}

You cannot assign a value to the constant PI field.

What is the difference between a constant and a static readonly field?

A static readonly field is very similar to a constant, except that the C# compiler does not have access to the value of a static read-only field at compile time, only at run time.

What are constants in C#?

Constants in C# are immutable values which are known at compile time and do not change for the life of the program. Constants are declared using the const keyword. Constants must be initialized as they are declared. You cannot assign a value to a constant after it isdeclared. An example is shown below.

using System;
class Circle
{
public const double PI = 3.14;
public Circle()
{
//Error : You can only assign a value to a constant field at the time of declaration
//PI = 3.15;
}
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Circle.PI);
}
}

What are Properties in C#?

Properties in C# are class members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

Explain the 3 types of properties in C# with an example?

1) Read Only Properties: Properties without a set accessor are considered read-only. In the above example FullName is read only property.
2) Write Only Properties: Properties without a get accessor are considered write-only. In the above example Country is write only property.
3) Read Write Properties: Properties with both a get and set accessor are considered read-write properties. In the above example FirstName and LastName are read write properties.

What are the advantages of properties in C#?

1) Properties can validate data before allowing a change. 2) Properties can transparently expose data on a class where that data is actually retrieved from some other source such as a database. 3) Properties can take an action when data is changed, such as raising an event or changing the value of other fields.

What is a static property. Give an example?

A property that is marked with a static keyword is considered as static property. This makes the property available to callers at any time, even if no instance of the class exists. In the example below PI is a static property.

using System;
class Circle
{
private static double _pi = 3.14;
public static double PI
{
get
{
return _pi;
}
}
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Circle.PI);
}
}

What is Connection Pooling?

Connection pooling is the ability of re-use your connection to the Database. This means if you enable Connection pooling in the connection object, actually you enable the re-use of the connection to more than one user.
The connection pooling is enabled by default in the connection object. If you disable the connection pooling, this means the connection object which you create will not be re-used to any other user than who create that object.

With Connection Pooling
SqlConnection con = new SqlConnection(@"Data Source=SQLEXPRESS;Initial Catalog=TestDB;Persist Security Info=True; User ID=id;Password=password;");
long startTicks = DateTime.Now.Ticks;
for (int i = 1; i <= 100; i++)
{
   con.Open();
   con.Close();
}
long endTicks = DateTime.Now.Ticks;
Console.WriteLine("Time taken : " + (endTicks - startTicks) + " ticks.");
con.Dispose();
Console.ReadKey();
// Output
// Time taken : 1290129 ticks.
Without Connection Pooling (add 'Pooling=false' in connection string)
 SqlConnection con = new SqlConnection(@"Data Source=SQLEXPRESS;Initial Catalog=TestDB;Persist Security Info=True; User ID=id;Password=password;Pooling=false;");
// Output
// Time taken : 35463546 ticks.

What is Object Pooling?

Object Pooling is something that tries to keep a pool of objects in memory to be re-used later and hence it will reduce the load of object creation to a great extent.
Object Pool is nothing but a container of objects that are ready for use. Whenever there is a request for a new object, the pool manager will take the request and it will be served by allocating an object from the pool.

What is a Destructor?

A Destructor has the same name as the class with a tilde character and is used to destroy an instance of a class.

Can a class have more than 1 destructor?

No, a class can have only 1 destructor.

Can structs in C# have destructors?

No, structs can have constructors but not destructors, only classes can have destructors.

Can you pass parameters to destructors?

No, you cannot pass parameters to destructors. Hence, you cannot overload destructors.

Can you explicitly call a destructor?

No, you cannot explicitly call a destructor. Destructors are invoked automatically by the garbage collector.

Why is it not a good idea to use Empty destructors?

When a class contains a destructor, an entry is created in the Finalize queue. When the destructor is called, the garbage collector is invoked to process the queue. If the destructor is empty, this just causes a needless loss of performance.

Is it possible to force garbage collector to run?

Yes, it possible to force garbage collector to run by calling the Collect() method, but this is not considered a good practice because this might create a performance over head. Usually the programmer has no control over when the garbage collector runs. The garbage collector checks for objects that are no longer being used by the application. If it considers an object eligible for destruction, it calls the destructor(if there is one) and reclaims the memory used to store the object.

Usually in .NET, the CLR takes care of memory management. Is there any need for a programmer to explicitly release memory and resources? If yes, why and how?

If the application is using expensive external resource, it is recommend to explicitly release the resource before the garbage collector runs and frees the object. We can do this by implementing the Dispose method from the IDisposable interface that performs the necessary cleanup for the object. This can considerably improve the performance of the application.

When do we generally use destructors to release resources?

If the application uses unmanaged resources such as windows, files, and network connections, we use destructors to release resources.

What is a partial class. Give an example?

A partial class is a class whose definition is present in 2 or more files. Each source file contains a section of the class, and all parts are combined when the application is compiled. To split a class definition, use the partial keyword as shown in the example below. Student class is split into 2 parts. The first part defines the study() method and the second part defines the Play() method. When we compile this program both the parts will be combined and compiled. Note that both the parts uses partial keyword and public access modifier.

using System;
namespace PartialClass
{
public partial class Student
{
public void Study()
{
Console.WriteLine("I am studying");
}
}
public partial class Student
{
public void Play()
{
Console.WriteLine("I am Playing");
}
}
public class Demo
{
public static void Main()
{
Student StudentObject = new Student();
StudentObject.Study();
StudentObject.Play();
}
}
}

It is very important to keep the following points in mind when creating partial classes.

1) All the parts must use the partial keyword.
2) All the parts must be available at compile time to form the final class.
3) All the parts must have the same access modifiers - public, private, protected etc.
4) Any class members declared in a partial definition are available to all the other parts.
5) The final class is the combination of all the parts at compile time.

What are the advantages of using partial classes?

When working on large projects, spreading a class over separate files enables multiple programmers to work on it at the same time.
When working with automatically generated source, code can be added to the class without having to recreate the source file. Visual Studio uses this approach when it creates Windows Forms, Web service wrapper code, and so on. You can create code that uses these classes without having to modify the file created by Visual Studio.

Can different parts of a partial class inherit from different interfaces?

Yes, different parts of a partial class can inherit from different interfaces.

Can you specify nested classes as partial classes?

Yes, nested classes can be specified as partial classes even if the containing class is not partial. An example is shown below.

class ContainerClass
{
public partial class Nested
{
void Test1() { }
}
public partial class Nested
{
void Test2() { }
}
}

How do you create partial methods?

To create a partial method we create the declaration of the method in one part of the partial class and implementation in the other part of the partial class. The implementation is optional. If the implementation is not provided, then the method and all the calls to the method are removed at compile time. Therefore, any code in the partial class can freely use a partial method, even if the implementation is not supplied. No compile-time or run-time errors will result if the method is called but not implemented. In summary a partial method declaration consists of two parts. The definition, and the implementation. These may be in separate parts of a partial class, or in the same part. If there is no implementation declaration, then the compiler optimizes away both the defining declaration and all calls to the method.
The following are the points to keep in mind when creating partial methods.
1) Partial method declarations must begin partial keyword.
2) The return type of a partial method must be void.
3) Partial methods can have ref but not out parameters.
4) Partial methods are implicitly private, and therefore they cannot be virtual.
5) Partial methods cannot be extern, because the presence of the body determines whether they are defining or implementing.

What is the use of partial methods?

Partial methods can be used to customize generated code. They allow for a method name and signature to be reserved, so that generated code can call the method but the developer can decide whether to implement the method. Much like partial classes, partial methods enable code created by a code generator and code created by a human developer to work together without run-time costs.

//Partial class with same name method:
public partial class Calculator
{
    public string Add()
    {
        return "";
    }
    public string Subtract()
    {
        return "";
    }
}
public partial class Calculator
{
    public string Multiply()
    {
        return "";
    }
    public string Add()
    {
        return "";
    }
}

There will be a compile time error when you try to compile this code! What happens at build time is the compiler combines all the members defined in all the partial definitions of the class into one. It will then try to compile it the usual way. In your case it will raise an error mentioning you already have defined a method with the same name.


Page 7 of 7