C# Interview Question and Answers with Example - Part 5


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



Views: 55

Can you declare a class or a struct as constant?

No, User-defined types including classes, structs, and arrays, cannot be const. Only the C# built-in types excluding System.Object may be declared as const. Use the readonly modifier to create a class, struct, or array that is initialized one time at runtime (for example in a constructor) and thereafter cannot be changed.

Does C# support const methods, properties, or events?

No, C# does not support const methods, properties, or events.

Can you change the value of a constant filed after its declaration?

No, you cannot change the value of a constant field after its declaration. In the example below, the constant field PI is always 3.14, and it cannot be changed even by the class itself. In fact, when the compiler encounters a constant identifier in C# source code (for example, PI), it substitutes the literal value directly into the intermediate language (IL) code that it produces. Because there is no variable address associated with a constant at run time, const fields cannot be passed by reference.
using System;
class Circle
{
public const double PI = 3.14;
}

How do you access a constant field declared in a class?

Constants are accessed as if they were static fields because the value of the constant is the same for all instances of the type. You do not use the static keyword to declare them. Expressions that are not in the class that defines the constant must use the class name, a period, and the name of the constant to access the constant. In the example below constant field PI can be accessed in the Main method using the class name and not the instance of the class. Trying to access a constant field using a class instance will generate a compile time error.

using System;
class Circle
{
public const double PI = 3.14;
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Circle.PI);
Circle C = new Circle();
// Error : PI cannot be accessed using an instance
// Console.WriteLine(C.PI);
}
}

What are Properties in C#. Explain with an example?

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.
In the example below _firstName and _lastName are private string variables which are accessible only inside the Customer class. _firstName and _lastName are exposed using FirstName and LastName public properties respectively. The get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels. The value keyword is used to define the value being assigned by the set accessor. The FullName property computes the full name of the customer. Full Name property is readonly, because it has only the get accessor. Properties that do not implement a set accessor are read only.
The code block for the get accessor is executed when the property is read and the code block for the set accessor is executed when the property is assigned a new value.

using System;
class Customer
{
// Private fileds not accessible outside the class.
private string _firstName = string.Empty;
private string _lastName = string.Empty;
private string _coutry = string.Empty;
// public FirstName property exposes _firstName variable
public string FirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
}
}
// public LastName property exposes _lastName variable
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
}
}
// FullName property is readonly and computes customer full name.
public string FullName
{
get
{
return _lastName + ", " + _firstName;
}
}
//Country Property is Write Only
public string Country
{
set
{
_coutry = value;
}
}
}
class MainClass
{
public static void Main()
{
Customer CustomerObject = new Customer();
//This line will call the set accessor of FirstName Property
CustomerObject.FirstName = "David";
//This line will call the set accessor of LastName Property
CustomerObject.LastName = "Boon";
//This line will call the get accessor of FullName Property
Console.WriteLine("Customer Full Name is : " + CustomerObject.FullName);
}
}

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. This article will try to explain this in detail. The example is for an Employee object, but you can make it general by using Object base class.
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.

Is it possible to create partial structs, interfaces and methods?

Yes, it is possible to create partial structs, interfaces and methods. We can create partial structs, interfaces and methods the same way as we create partial classes.

Will the following code compile?

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

No, a compile time error will be generated stating "Cannot create an instance of the abstract class or interface "PartialClass.Student". This is because, if any part is declared abstract, then the whole class becomes abstract. Similarly if any part is declared sealed, then the whole class becomes sealed and if any part declares a base class, then the whole class inherits that base class.

Can you create partial delegates and enumerations?

No, you cannot create partial delegates and enumerations.



Views: 55