C# Interview Question and Answers with Example - Part 4


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



Views: 48

When to use abstract class?

When we want to provide some default functionality to related classes then use abstract class.

When to use abstract class?

When classes are not related but functionality is common to all classes then use interface.
eg. dog and employee class
common method : Walk() but implementation is different.

What is yield keyword in C#?

The functionality that yield keyword provides is that when iterating a list, we can read an element of the loop, return to the calling code and go back to the loop again at the same point, from where it left the loop and continue processing the records in the loop.
Here, in below example FilterData() method return integer which are greater than 50.

Ex:
static void Main(string[] args)
{
    List<int> intList = new List<int>() { 10, 20, 90, 30, 40, 70, 45, 99 };
    IEnumerable<int> outputList = FilterData(intList);
    foreach (var item in outputList)
    {
        Console.WriteLine(item);
    }
    Console.ReadKey();
}
public static IEnumerable<int> FilterData(List<int> intList)
{
    Console.WriteLine("Inside filter");
    foreach (var item in intList)
    {
        if (item > 50)
            yield return item;
    }
}
// OUTPUT:
Inside filter
90
70
99

What is Types and Type Members?

Types:
Classes, structs, interfaces, delegates are examples of Types.
Type can have only public or internal as access modifiers.

Type Members:
Fields, properties, constructor, methods that reside in a Type are called as type members.
Type members can have any access modifiers.

What is access modifiers in C#?

Access modifiers are keywords used to specify the declared accessibility of a member or a type.

What are the different types of access modifiers in C#?

Public
The public type or member can be accessed by any other code in the same assembly or another assembly that references it.

Private
The 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.

Internal
The 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 is default access modifiers of Types i.e for Classes or Interfaces?

Internal

What is default access modifiers of Type Members i.e for fields or Methods?

Private

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?

namespace ConsoleApplication1
{
    private class Test
    {
        public static void Main()
        {
        }
    }
}

No, a compile time error will be generated stating "Elements defined in a namespace 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.

Will the following code compile?

using System;
interface ICalculator
{
public void Add();
}

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.

What are the 2 broad classifications of fields in C#?

Instance fields
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.

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


Views: 48