HI WELCOME TO SIRIS

C# Interview Questions by topic part 3

Leave a Comment

C# Interview Questions related to Interfaces.

Explain what is an Interface in C#?
An Interface in C# is created using the interface keyword. An example is shown below.

using System;
namespace Interfaces
{
interface IBankCustomer
{
void DepositMoney();
void WithdrawMoney();
}
public class Demo : IBankCustomer
{
public void DepositMoney()
{
Console.WriteLine("Deposit Money");
}

public void WithdrawMoney()
{
Console.WriteLine("Withdraw Money");
}

public static void Main()
{
Demo DemoObject = new Demo();
DemoObject.DepositMoney();
DemoObject.WithdrawMoney();
}
}
}

In our example we created IBankCustomer interface. The interface declares 2 methods.
1. void DepositMoney();
2. void WithdrawMoney();

Notice that method declarations does not have access modifiers like public, private, etc. By default all interface members are public. It is a compile time error to use access modifiers on interface member declarations. Also notice that the interface methods have only declarations and not implementation. It is a compile time error to provide implementation for any interface member. In our example as the Demo class is inherited from the IBankCustomer interface, the Demo class has to provide the implementation for both the methods (WithdrawMoney() and DepositMoney()) that is inherited from the interface. If the class fails to provide implementation for any of the inherited interface member, a compile time error will be generated. Interfaces can consist of methods, properties, events, indexers, or any combination of those four member types. When a class or a struct inherits an interface, the class or struct must provide implementation for all of the members declared in the interface. The interface itself provides no functionality that a class or struct can inherit in the way that base class functionality can be inherited. However, if a base class implements an interface, the derived class inherits that implementation.

Can an Interface contain fields?
No, an Interface cannot contain fields.

What is the difference between class inheritance and interface inheritance?
Classes and structs can inherit from interfaces just like how classes can inherit a base class or struct. However there are 2 differences.
1. A class or a struct can inherit from more than one interface at the same time where as A class or a struct cannot inherit from more than one class at the same time. An example depicting the same is shown below.

using System;
namespace Interfaces
{
interface Interface1
{
void Interface1Method();
}
interface Interface2
{
void Interface2Method();
}
class BaseClass1
{
public void BaseClass1Method()
{
Console.WriteLine("BaseClass1 Method");
}
}
class BaseClass2
{
public void BaseClass2Method()
{
Console.WriteLine("BaseClass2 Method");
}
}

//Error : A class cannot inherit from more than one class at the same time
//class DerivedClass : BaseClass1, BaseClass2
//{
//}

//A class can inherit from more than one interface at the same time
public class Demo : Interface1, Interface2
{
public void Interface1Method()
{
Console.WriteLine("Interface1 Method");
}

public void Interface2Method()
{
Console.WriteLine("Interface2 Method");
}

public static void Main()
{
Demo DemoObject = new Demo();
DemoObject.Interface1Method();
DemoObject.Interface2Method();
}
}
}

2. When a class or struct inherits an interface, it inherits only the method names and signatures, because the interface itself contains no implementations.

Can an interface inherit from another interface?
Yes, an interface can inherit from another interface. It is possible for a class to inherit an interface multiple times, through base classes or interfaces it inherits. In this case, the class can only implement the interface one time, if it is declared as part of the new class. If the inherited interface is not declared as part of the new class, its implementation is provided by the base class that declared it. It is possible for a base class to implement interface members using virtual members; in that case, the class inheriting the interface can change the interface behavior by overriding the virtual members.

Can you create an instance of an interface?
No, you cannot create an instance of an interface.

If a class inherits an interface, what are the 2 options available for that class?
Option 1: Provide Implementation for all the members inheirted from the interface.

namespace Interfaces
{
interface Interface1
{
void Interface1Method();
}

class BaseClass1 : Interface1
{
public void Interface1Method()
{
Console.WriteLine("Interface1 Method");
}
public void BaseClass1Method()
{
Console.WriteLine("BaseClass1 Method");
}
}
}

Option 2: If the class does not wish to provide Implementation for all the members inheirted from the interface, then the class has to be marked as abstract.

namespace Interfaces
{
interface Interface1
{
void Interface1Method();
}

abstract class BaseClass1 : Interface1
{
abstract public void Interface1Method();
public void BaseClass1Method()
{
Console.WriteLine("BaseClass1 Method");
}
}
}

A class inherits from 2 interfaces and both the interfaces have the same method name as shown below. How should the class implement the drive method for both Car and Bus interface?
namespace Interfaces
{
interface Car
{
void Drive();
}
interface Bus
{
void Drive();
}

class Demo : Car,Bus
{
//How to implement the Drive() Method inherited from Bus and Car
}
}

To implement the Drive() method use the fully qualified name as shown in the example below. To call the respective interface drive method type cast the demo object to the respective interface and then call the drive method.

using System;
namespace Interfaces
{
interface Car
{
void Drive();
}
interface Bus
{
void Drive();
}

class Demo : Car,Bus
{
void Car.Drive()
{
Console.WriteLine("Drive Car");
}
void Bus.Drive()
{
Console.WriteLine("Drive Bus");
}

static void Main()
{
Demo DemoObject = new Demo();
((Car)DemoObject).Drive();
((Bus)DemoObject).Drive();
}
}
}

What do you mean by "Explicitly Implemeting an Interface". Give an example?
If a class is implementing the inherited interface member by prefixing the name of the interface, then the class is "Explicitly Implemeting an Interface member". The disadvantage of Explicitly Implemeting an Interface member is that, the class object has to be type casted to the interface type to invoke the interface member. An example is shown below.

using System;
namespace Interfaces
{
interface Car
{
void Drive();
}

class Demo : Car
{
// Explicit implementation of an interface member
void Car.Drive()
{
Console.WriteLine("Drive Car");
}

static void Main()
{
Demo DemoObject = new Demo();

//DemoObject.Drive();
// Error: Cannot call explicitly implemented interface method
// using the class object.
// Type cast the demo object to interface type Car
((Car)DemoObject).Drive();
}
}
}

C# Interview Questions on partial classes, structs and methods.


What is a partial class. Give an example?
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?
1. When working on large projects, spreading a class over separate files enables multiple programmers to work on it at the same time.

2. 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.

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.

Nested Types in C#


What is a nested type. Give an example?
A type(class or a struct) defined inside another class or struct is called a nested type. An example is shown below. InnerClass is inside ContainerClass, Hence InnerClass is called as nested class.

using System;
namespace Nested
{
  class ContainerClass
  {
    class InnerClass
    {
      public string str = "A string variable in nested class";
    }

    public static void Main()
    {
      InnerClass nestedClassObj = new InnerClass();
      Console.WriteLine(nestedClassObj.str);
    }
  }
}

Will the following code compile?
using System;
namespace Nested
{
  class ContainerClass
  {
    class InnerClass
    {
      public string str = "A string variable in nested class";
    }
  }

  class Demo
  {
    public static void Main()
    {
      InnerClass nestedClassObj = new InnerClass();
      Console.WriteLine(nestedClassObj.str);
    }
  }
}

No, the above code will generate a compile time error stating - The type or namespace name 'InnerClass' could not be found (are you missing a using directive or an assembly reference?). This is bcos InnerClass is inside ContainerClass and does not have any access modifier. Hence inner class is like a private member inside ContainerClass. For the above code to compile and run, we should make InnerClass public and use the fully qualified name when creating the instance of the nested class as shown below.

using System;
namespace Nested
{
  class ContainerClass
  {
    public class InnerClass
    {
      public string str = "A string variable in nested class";
    }
  }

  class Demo
  {
    public static void Main()
    {
      ContainerClass.InnerClass nestedClassObj = new ContainerClass.InnerClass();
      Console.WriteLine(nestedClassObj.str);
    }
  }
}


Can the nested class access, the Containing class. Give an example?
Yes, the nested class, or inner class can access the containing or outer class as shown in the example below. Nested types can access private and protected members of the containing type, including any inherited private or protected members.

using System;
namespace Nested
{
  class ContainerClass
  {
    string OuterClassVariable = "I am an outer class variable";
   
    public class InnerClass
    {
      ContainerClass ContainerClassObject = new ContainerClass();
      string InnerClassVariable = "I am an Inner class variable";
      public InnerClass()
      {
        Console.WriteLine(ContainerClassObject.OuterClassVariable);
        Console.WriteLine(this.InnerClassVariable);
      }
    }
  }

  class Demo
  {
    public static void Main()
    {
      ContainerClass.InnerClass nestedClassObj = new ContainerClass.InnerClass();
    }
  }
}

What is the ouput of the following program?
using System;
namespace Nested
{
  class ContainerClass
  {
    public ContainerClass()
    {
      Console.WriteLine("I am a container class");
    }

    public class InnerClass : ContainerClass
    {
      public InnerClass()
      {
        Console.WriteLine("I am an inner class");
      }
    }
  }

  class DemoClass : ContainerClass.InnerClass
  {
    public DemoClass()
    {
      Console.WriteLine("I am a Demo class");
    }
    public static void Main()
    {
      DemoClass DC = new DemoClass();
    }
  }
}

Output:
I am a container class
I am an inner class
I am a Demo class

The above program has used the concepts of inheritance and nested classes. The ContainerClass is at the top in the inheritance chain. The nested InnerClass derives from outer ContainerClass. Finally the DemoClass derives from nested InnerClass. As all the 3 classes are related by inheritance we have the above output.

C# Interview Questions on Destructors


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.

C# Interview Questions on constructors


What is a constructor in C#?
Constructor is a class method that is executed when an object of a class is created. Constructor has the same name as the class, and usually used to initialize the data members of the new object.

In C#, What will happen if you do not explicitly provide a constructor for a class?
If you do not provide a constructor explicitly for your class, C# will create one by default that instantiates the object and sets all the member variables to their default values.

Structs are not reference types. Can structs have constructors?
Yes, even though Structs are not reference types, structs can have constructors.

We cannot create instances of static classes. Can we have constructors for static classes?
Yes, static classes can also have constructors.

Can you prevent a class from being instantiated?
Yes, a class can be prevented from being instantiated by using a private constructor as shown in the example below.

using System;
namespace TestConsole
{
  class Program
  {
    public static void Main()
    {
      //Error cannot create instance of a class with private constructor
      SampleClass SC = new SampleClass();
    }
  }
  class SampleClass
  {
    double PI = 3.141;
    private SampleClass()
    {
    }
  }
}


Can a class or a struct have multiple constructors?
Yes, a class or a struct can have multiple constructors. Constructors in csharp can be overloaded.

Can a child class call the constructor of a base class?
Yes, a child class can call the constructor of a base class by using the base keyword as shown in the example below.

using System;
namespace TestConsole
{
  class BaseClass
  {
    public BaseClass(string str)
    {
      Console.WriteLine(str);
    }
  }

  class ChildClass : BaseClass
  {
    public ChildClass(string str): base(str)
    {
    }

    public static void Main()
    {
      ChildClass CC = new ChildClass("Calling base class constructor from child class");
    }
  }
}

If a child class instance is created, which class constructor is called first - base class or child class?
When an instance of a child class is created, the base class constructor is called before the child class constructor. An example is shown below.

using System;
namespace TestConsole
{
  class BaseClass
  {
    public BaseClass()
    {
      Console.WriteLine("I am a base class constructor");
    }
  }
  class ChildClass : BaseClass
  {
    public ChildClass()
    {
      Console.WriteLine("I am a child class constructor");
    }
    public static void Main()
    {
      ChildClass CC = new ChildClass();
    }
  }
}

Will the following code compile?
using System;
namespace TestConsole
{
  class BaseClass
  {
    public BaseClass(string str)
    {
      Console.WriteLine(str);
    }
  }
  class ChildClass : BaseClass
  {
    public ChildClass()
    {
      Console.WriteLine("I am a child class constructor");
    }
    public static void Main()
    {
      ChildClass CC = new ChildClass();
    }
  }
}

No, the above code will not compile. This is because, if a base class does not offer a default constructor, the derived class must make an explicit call to a base class constructor by using the base keyword as shown in the example below.

using System;
namespace TestConsole
{
  class BaseClass
  {
    public BaseClass(string str)
    {
      Console.WriteLine(str);
    }
  }
  class ChildClass : BaseClass
  {
    //Call the base class contructor from child class
    public ChildClass() : base("A call to base class constructor")
    {
      Console.WriteLine("I am a child class constructor");
    }
    public static void Main()
    {
      ChildClass CC = new ChildClass();
    }
  }
}

Can a class have static constructor?
Yes, a class can have static constructor. Static constructors are called automatically, immediately before any static fields are accessed, and are generally used to initialize static class members. It is called automatically before the first instance is created or any static members are referenced. Static constructors are called before instance constructors. An example is shown below.

using System;
namespace TestConsole
{
  class Program
  {
    static int I;
    static Program()
    {
      I = 100;
      Console.WriteLine("Static Constructor called");
    }
    public Program()
    {
      Console.WriteLine("Instance Constructor called");
    }
    public static void Main()
    {
      Program P = new Program();
    }
  }
}

Can you mark static constructor with access modifiers?
No, we cannot use access modifiers on static constructor.

Can you have parameters for static constructors?
No, static constructors cannot have parameters.

What happens if a static constructor throws an exception?
If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

Give 2 scenarios where static constructors can be used?
1. A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
2. Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

C# Interview Questions on Methods / Functions


Is the following code legal?
using System;
namespace Demo
{
 class Program
 {
  public static void Main()
  {

  }
  public void Sum(int FirstNumber, int SecondNumber)
  {
   int Result = FirstNumber + SecondNumber;
  }

  public int Sum(int FirstNumber, int SecondNumber)
  {
   int Result = FirstNumber + SecondNumber;
  }
 }
}

No, The above code does not compile. You cannot overload a method based on the return type. To overload a method in C# either the number or type of parameters should be different. In general the return type of a method is not part of the signature of the method for the purposes of method overloading. However, it is part of the signature of the method when determining the compatibility between a delegate and the method that it points to.

What is the difference between method parameters and method arguments. Give an example?
In the example below FirstNumber and SecondNumber are method parameters where as FN and LN are method arguments. The method definition specifies the names and types of any parameters that are required. When calling code calls the method, it provides concrete values called arguments for each parameter. The arguments must be compatible with the parameter type but the argument name (if any) used in the calling code does not have to be the same as the parameter named defined in the method.

using System;
namespace Demo
{
 class Program
 {
  public static void Main()
  {
   int FN = 10;
   int SN = 20;
   //FN and LN are method arguments
   int Total = Sum(FN, SN);
   Console.WriteLine(Total);
  }
  //FirstNumber and SecondNumber are method parameters
  public static int Sum(int FirstNumber, int SecondNumber)
  {
   int Result = FirstNumber + SecondNumber;
   return Result;
  }
 }
}


Explain the difference between passing parameters by value and passing parameters by reference with an example?
We can pass parameters to a method by value or by reference. By default all value types are passed by value where as all reference types are passed by reference. By default, when a value type is passed to a method, a copy is passed instead of the object itself. Therefore, changes to the argument have no effect on the original copy in the calling method.An example is shown below.

using System;
namespace Demo
{
 class Program
 {
  public static void Main()
  {
   int I = 10;
   int K = Function(I);

   Console.WriteLine("I = " + I);
   Console.WriteLine("K = " + K);
  }
  public static int Function(int Number)
  {
   int ChangedValue = Number + 1;
   return ChangedValue;
  }
 }
}

By default, reference types are passed by reference. When an object of a reference type is passed to a method, the reference points to the original object, not a copy of the object. Changes made through this reference will therefore be reflected in the calling method. Reference types are created by using the class keyword as shown in the example below.

using System;
namespace Demo
{
 class Program
 {
  public static void Main()
  {
   ReferenceTypeExample Object = new ReferenceTypeExample();
   Object.Number = 20;
   Console.WriteLine("Original Object Value = " + Object.Number);
   Function(Object);
   Console.WriteLine("Object Value after passed to the method= " + Object.Number);
  }
  public static void Function(ReferenceTypeExample ReferenceTypeObject)
  {
   ReferenceTypeObject.Number = ReferenceTypeObject.Number + 5;
  }
 }

 class ReferenceTypeExample
 {
  public int Number;
 }
}

Can you pass value types by reference to a method?
Yes, we can pass value types by by reference to a method. An example is shown below.

using System;
namespace Demo
{
 class Program
 {
  public static void Main()
  {
   int I = 10;
   Console.WriteLine("Value of I before passing to the method = " + I);
   Function(ref I);
   Console.WriteLine("Value of I after passing to the method by reference= " + I);
  }
  public static void Function(ref int Number)
  {
   Number = Number + 5;
  }
 }
}

If a method's return type is void, can you use a return keyword in the method?
Yes, Even though a method's return type is void, you can use the return keyword to stop the execution of the method as shown in the example below.
using System;
namespace Demo
{
 class Program
 {
  public static void Main()
  {
   SayHi();
  }
  public static void SayHi()
  {
   Console.WriteLine("Hi");
   return;
   Console.WriteLine("This statement will never be executed");
  }
 }
}

C# Interview Questions on Properties


Why do we need Properties - Video 
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 a virtual property. Give an example? 
A property that is marked with virtual keyword is considered virtual property. Virtual properties enable derived classes to override the property behavior by using the override keyword. In the example below FullName is virtual property in the Customer class. BankCustomer class inherits from Customer class and overrides the FullName virtual property. In the output you can see the over riden implementation. A property overriding a virtual property can also be sealed, specifying that for derived classes it is no longer virtual.


using System;
class Customer
{
   private string _firstName = string.Empty;
   private string _lastName = string.Empty;

   public string FirstName
   {
      get
      {
         return _firstName;
      }
      set
      {
         _firstName = value;
      }
   }
   public string LastName
   {
      get
      {
         return _lastName;
      }
      set
      {
         _lastName = value;
      }
   }
   // FullName is virtual
   public virtual string FullName
   {
      get
      {
         return _lastName + ", " + _firstName;
      }
   }
}
class BankCustomer : Customer
{
   // Overiding the FullName virtual property derived from customer class
   public override string FullName
   {
      get
      {
         return "Mr. " + FirstName + " " + LastName;
      }
   }
}
class MainClass
{
   public static void Main()
   {
      BankCustomer BankCustomerObject = new BankCustomer();
      BankCustomerObject.FirstName = "David";
      BankCustomerObject.LastName = "Boon";
      Console.WriteLine("Customer Full Name is : " + BankCustomerObject.FullName);
   }
}

What is an abstract property. Give an example? 
A property that is marked with abstract keyword is considered abstract property. An abstract property should not have any implementation in the class. The derived classes must write their own implementation. In the example below FullName property is abstract in the Customer class. BankCustomer class overrides the inherited abstract FullName property with its own implementation.


using System;
abstract class Customer
{
   private string _firstName = string.Empty;
   private string _lastName = string.Empty;

   public string FirstName
   {
      get
      {
         return _firstName;
      }
      set
      {
         _firstName = value;
      }
   }
   public string LastName
   {
      get
      {
         return _lastName;
      }
      set
      {
         _lastName = value;
      }
   }
   // FullName is abstract
   public abstract string FullName
   {
      get;
   }
}
class BankCustomer : Customer
{
   // Overiding the FullName abstract property derived from customer class
   public override string FullName
   {
      get
      {
         return "Mr. " + FirstName + " " + LastName;
      }
   }
}
class MainClass
{
   public static void Main()
   {
      BankCustomer BankCustomerObject = new BankCustomer();
      BankCustomerObject.FirstName = "David";
      BankCustomerObject.LastName = "Boon";
      Console.WriteLine("Customer Full Name is : " + BankCustomerObject.FullName);
   }
}

Can you use virtual, override or abstract keywords on an accessor of a static property? 
No, it is a compile time error to use a virtual, abstract or override keywords on an accessor of a static property.

C# Interview Questions on Constants


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);
   }
}

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 filed 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);
   }
}


0 comments:

Post a Comment

Note: only a member of this blog may post a comment.