HI WELCOME TO SIRIS

C# Interview Questions by topic part 4

Leave a Comment

Why should you override the ToString() method


Why should you override the ToString() method? 
All types in .Net inherit from system.object directly or indirectly. Because of this inheritance, every type in .Net inherit the ToString() method from System.Object class. Consider the example below.

using System;
public class MainClass
{
  public static void Main()
  {
   int Number = 10;
   Console.WriteLine(Number.ToString());
  }
}

In the above example Number.ToString() method will correctly give the string representaion of int 10, when you call the ToString() method.

If you have a Customer class as shown in the below example and when you call the ToString() method the output doesnot make any sense. Hence you have to override the ToString() method, that is inherited from the System.Object class.

using System;
public class Customer
{
 public string FirstName;
 public string LastName;
}
public class MainClass
{
 public static void Main()
 {
  Customer C = new Customer();
  C.FirstName = "David";
  C.LastName = "Boon";
  Console.WriteLine(C.ToString());
 }
}


The code sample below shows how to override the ToString() method in a class, that would give the output you want.


using System;
public class Customer
{
  public string FirstName;
  public string LastName;

  public override string ToString()
  {
    return LastName + ", " + FirstName;
  }
}
public class MainClass
{
  public static void Main()
  {
    Customer C = new Customer();
    C.FirstName = "David";
    C.LastName = "Boon";
    Console.WriteLine(C.ToString());
  }
}

Conclusion : If you have a class or a struct, make sure you override the inherited ToString() method.

C# Interview Questions on Fields


What are the 2 broad classifications of fields in C#?
1. Instance fields
2. Static fields

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.

C# Interview Questions on polymorphism


Explain polymorphism in C# with a simple example? 
Polymorphism allows you to invoke derived class methods through a base class reference during run-time. An example is shown below.
using System;
public class DrawingObject
{
public virtual void Draw()
{
Console.WriteLine("I am a drawing object.");
}
}
public class Triangle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I am a Triangle.");
}
}
public class Circle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I am a Circle.");
}
}
public class Rectangle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I am a Rectangle.");
}
}
public class DrawDemo
{
public static void Main()
{
DrawingObject[] DrawObj = new DrawingObject[4];

DrawObj[0] = new Triangle();
DrawObj[1] = new Circle();
DrawObj[2] = new Rectangle();
DrawObj[3] = new DrawingObject();

foreach (DrawingObject drawObj in DrawObj)
{
drawObj.Draw();
}
}
}

When can a derived class override a base class member? 
A derived class can override a base class member only if the base class member is declared as virtual or abstract.

What is the difference between a virtual method and an abstract method? 
A virtual method must have a body where as an abstract method should not have a body.

Can fields inside a class be virtual?No, Fields inside a class cannot be virtua. Only methods, properties, events and indexers can be virtual.

Give an example to show for hiding base class methods? 
Use the new keyword to hide a base class method in the derived class as shown in the example below.
using System;
public class BaseClass
{
public virtual void Method()
{
Console.WriteLine("I am a base class method.");
}
}
public class DerivedClass : BaseClass
{
public new void Method()
{
Console.WriteLine("I am a child class method.");
}

public static void Main()
{
DerivedClass DC = new DerivedClass();
DC.Method();
}
}

Can you access a hidden base class method in the derived class? 
Yes, Hidden base class methods can be accessed from the derived class by casting the instance of the derived class to an instance of the base class as shown in the example below.
using System;
public class BaseClass
{
public virtual void Method()
{
Console.WriteLine("I am a base class method.");
}
}
public class DerivedClass : BaseClass
{
public new void Method()
{
Console.WriteLine("I am a child class method.");
}

public static void Main()
{
DerivedClass DC = new DerivedClass();
((BaseClass)DC).Method();
}
}

C# Interview Questions on Access Modifiers


What are Access Modifiers in C#? 
In C# there are 5 different types of Access Modifiers.
Public 
The public type or member can be accessed by any other code in the same assembly or another assembly that references it.

PrivateThe type or member can only be accessed by code in the same class or struct.

Protected
The type or member can only be accessed by code in the same class or struct, or in a derived class.

InternalThe type or member can be accessed by any code in the same assembly, but not from another assembly.

Protected Internal 
The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.

What are Access Modifiers used for?Access Modifiers are used to control the accessibilty of types and members with in the types.

Can you use all access modifiers for all types? 
No, Not all access modifiers can be used by all types or members in all contexts, and in some cases the accessibility of a type member is constrained by the accessibility of its containing type.

Can derived classes have greater accessibility than their base types?No, Derived classes cannot have greater accessibility than their base types. For example the following code is illegal.
using System;
internal class InternalBaseClass
{
   public void Print()
   {
      Console.WriteLine("I am a Base Class Method");
   }
}
public class PublicDerivedClass : InternalBaseClass
{
   public static void Main()
   {
      Console.WriteLine("I am a Public Derived Class Method");
   }
}


When you compile the above code an error will be generated stating "Inconsistent accessibility: base class InternalBaseClass is less accessible than class PublicDerivedClass".To make this simple, you cannot have a public class B that derives from an internal class A. If this were allowed, it would have the effect of making A public, because all protected or internal members of A are accessible from the derived class.


Is the following code legal? 

using System;
private class Test
{
   public static void Main()
   {
   }
}


No, a compile time error will be generated stating "Namespace elements cannot be explicitly declared as private, protected, or protected internal"

Can you declare struct members as protected? 
No, struct members cannot be declared protected. This is because structs do not support inheritance.

Can the accessibility of a type member be greater than the accessibility of its containing type?No, the accessibility of a type member can never be greater than the accessibility of its containing type. For example, a public method declared in an internal class has only internal accessibility.

Can destructors have access modifiers? 
No, destructors cannot have access modifiers.

What does protected internal access modifier mean?The protected internal access means protected OR internal, not protected AND internal. In simple terms, a protected internal member is accessible from any class in the same assembly, including derived classes. To limit accessibility to only derived classes in the same assembly, declare the class itself internal, and declare its members as protected.

What is the default access modifier for a class,struct and an interface declared directly with a namespace? 
internal

Will the following code compile?
using System;
interface IExampleInterface
{
   public void Save();
}

No, you cannot specify access modifer for an interface member. Interface members are always public.

Can you specify an access modifier for an enumeration? 
Enumeration members are always public, and no access modifiers can be specified.

C# Interview Questions on Abstract and Sealed Class Members


What is an abstract class? 
An abstract class is an incomplete class and must be implemented in a derived class.

Can you create an instance of an abstract class?No, abstract classes are incomplete and you cannot create an instance of an abstract class.

What is a sealed class? 
A sealed class is a class that cannot be inherited from. This means, If you have a class called Customer that is marked as sealed. No other class can inherit from Customer class. For example, the below code generates a compile time error "MainClass cannot derive from sealed type Customer.
using System;
public sealed class Customer
{
}
public class MainClass : Customer
{
public static void Main()
{
}
}

What are abstract methods? 
Abstract methods are methods that only the declaration of the method and no implementation.

Will the following code compile?using System;
public abstract class Customer
{
public abstract void Test()
{
Console.WriteLine("I am customer");
}
}
public class MainClass
{
public static void Main()
{
}
}
No, abstract methods cannot have body. Hence, the above code will generate a compile time error stating "Customer.Test() cannot declare a body because it is marked abstract"

Is the following code legal? 
using System;
public class Customer
{
public abstract void Test();
}
public class MainClass
{
public static void Main()
{
}
}

No, if a class has even a single abstract member, the class has to be marked abstract. Hence the above code will generate a compile time error stating "Customer.Test() is abstract but it is contained in nonabstract class Customer"

How can you force derived classes to provide new method implementations for virtual methods?
Abstract classes can be used to force derived classes to provide new method implementations for virtual methods. An example is shown below.
public class BaseClass
{
public virtual void Method()
{
// Original Implementation.
}
}

public abstract class AbstractClass : BaseClass
{
public abstract override void Method();
}

public class NonAbstractChildClass : AbstractClass
{
public override void Method()
{
// New implementation.
}
}

When an abstract class inherits a virtual method from a base class, the abstract class can override the virtual method with an abstract method. If a virtual method is declared abstract, it is still virtual to any class inheriting from the abstract class. A class inheriting an abstract method cannot access the original implementation of the method. In the above example, Method() on class NonAbstractChildClass cannot call Method() on class BaseClass. In this way, an abstract class can force derived classes to provide new method implementations for virtual methods.

Can a sealed class be used as a base class? 
No, sealed class cannot be used as a base class. A compile time error will be generated.

Will the following code compile?public abstract sealed class Test
{
public virtual void Method()
{
}
}
No, a class cannot be marked as sealed and abstract at the same time. This is because by definition, a sealed class cannot be a base class and an abstract class can only be a base class.

C# Interview Questions on Inheritance


What are the 4 pillars of any object oriented programming language?
1.
 Abstraction
2. Inheritance
3. Encapsulation
4. Polymorphism

Do structs support inheritance?No, structs do not support inheritance, but they can implement interfaces.

What is the main advantage of using inheritance? 
Code reuse

Is the following code legal?class ChildClass : ParentClassA, ParentClassB
{

No, a child class can have only one base class. You cannot specify 2 base classes at the same time. C# supports single class inheritance only. Therefore, you can specify only one base class to inherit from. However, it does allow multiple interface inheritance.

What will be the output of the following code? 
using System;
public class BaseClass
{
public BaseClass()
{
Console.WriteLine("I am a base class");
}
}
public class ChildClass : BaseClass
{
public ChildClass()
{
Console.WriteLine("I am a child class");
}
static void Main()
{
ChildClass CC = new ChildClass();
}
}
Output: 
I am a base class
I am a child class
This is because base classes are automatically instantiated before derived classes. Notice the output, The BaseClass constructor executed before the ChildClass constructor.

Does C# support multiple class inheritance?No, C# supports single class inheritance only. However classes can implement multiple interfaces at the same time.

0 comments:

Post a Comment

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