Basic Interview Tips In C#



C#

In this article, I am going to explain the following C# basics concepts.

  1. Value types & reference types
  2. Access Modifiers in C#
  3. Understanding Classes and other types

    • class (Abstract, partial, sealed, static etc.)
    • enum
    • struct
    • interface

  4. Understanding Partial Types and Partial Methods.
  5. use of ‘typeof’ keyword in C#.
  6. Calling multiple constructors of a class with single object creation.
  7. Understanding the output and behavior of C# basic code snippet.
  8. Implement and call the methods of the interfaces & the base class with the same name.
  9. Usage of ‘ref’ & ‘out’ keyword in C#.
  10. Using ‘params’ & ‘dynamic’ in method parameter.

I will be explaining all the topics, mentioned above in depth but the explanation will be more focused on the interview preparation i.e. I will explain all those things in the context of an interview. Actually, in the recent past, I have gone through dozens of interviews and I would like to share the experience with the other developers.

I am going to start with the very basic concepts and the purpose of this article is that the readers of this article can make themselves ready for C# interviews.

Value types & reference types

In C#, types have been divided into 2 parts, value types and the reference types. The value types directly store the data in the stack portion of RAM whereas the reference type stores reference of the data in the stack and save the actual data in heap but this is a half-truth statement. I will explain about it later to prove why it’s half-truth.
C#

Value types

A value type contains its data directly and it is stored in the stack of memory. Examples of some built-in value types are Numeric types (sbyte, byte, short, int, long, float, double, decimal), char, bool, IntPtr, date, Struct and Enum is the value type.

If I need to create a new value type, then I can use structs to create a new value type. I can also use enum keyword to create a value type of enum type.

Reference types

Reference types store the address of their data i.e. pointer on the stack and actual data is stored in heap area of the memory. The heap memory is managed by the garbage collector.

As I said, the reference type does not store its data directly, so assigning a reference type value to another reference type variable creates a copy of the reference address (pointer) and assign it to the 2nd reference variable. Thus, now both the reference variables have the same address or pointer for which an actual data is stored in heap. If I make any change in one variable, then that value will also be reflected in another variable.

In some cases, it is not valid like when reallocating memory, it may update only one variable for which new memory allocation has been done.

Suppose you are passing an object of customer class, let's say “objCustomer” inside a method “Modify(…)” and then re-allocate the memory inside the “Modify(…)” method & provide its properties value. In that case, customer object “objCustomer” inside the “Modify(…)” will have different value and those change will not be available to the variable “objCustomer” accessed outside of “Modify(…)”.

You can also take the example of String class. ‘string’ is the best example for this scenario because in the case of a string, each time new memory is allocated.

I will explain about all those scenarios in depth in “Usage of ‘ref’ & ‘out’ keyword in C#” & “Understanding the behavior of ‘string’ in C#” section of this article.

Understanding Classes and other types

The table is given below to understand Classes and other types. If you are aware of all the behaviors of the classes and other types, then you can skip this section and move to next section. I will explain all those things one by one for the developers, who are not aware of it.

C#
Note

You can see that static class can inherit a class. I have written no but used the * notation with that. It means a static class cannot inherit any other class but must inherit System.Object. Thus, we can also write the System.Object Class name in the inheritance list but there is no need to write the name System.Object explicitly because all the classes are being inherited from System.Object implicitly and we do not need to write it explicitly.

What are the different types of classes we can have?

We can have an abstract class, partial class, static class, sealed class, nested class & concrete class (simple class).

C#
Static Class

  1. static class Student {  
  2.     public static int StudentId {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public static string StudentName {  
  7.         get;  
  8.         set;  
  9.     }  
  10. }  
Static Partial Class
  1. public static partial class Student {  
  2.     public static int StudentId {  
  3.         get;  
  4.         set;  
  5.     } = 1;  
  6.     public new static string ToString() {  
  7.         return $ "Student Id is {StudentId:0000} and name is {StudentName}";  
  8.     }  
  9. }  
  10. public static partial class Student {  
  11.     public static string StudentName {  
  12.         get;  
  13.         set;  
  14.     } = "Banketeshvar Narayan";  
  15. }  
  1. I cannot create an instance of the static class.

    C#

  2. Static classes cannot have the instance constructors but it can have a static constructor.

    The code snippet, mentioned below will give compile time error.
    1. static class MyStaticClass {  
    2.     MyStaticClass() {}  
    3. }  
    Error

    CS0710 Static classes cannot have instance constructors

    The code snippet, mentioned below will compile successfully. 
    1. static class MyStaticClass {  
    2.     static MyStaticClass() {}  
    3. }  
  3. Static classes cannot implement the interfaces.

    The code snippet, mentioned below will give compile time error.
    1. static class MyStaticClass: IInterface {  
    2.     static MyStaticClass() {}  
    3. }  
    Error

    CS0714 'MyStaticClass': static classes cannot implement interfaces

  4. A static class cannot derive from type. Static classes must derive from an object.

    C#
  5. A static class cannot be a base class.

    The code snippet, mentioned below will give compile time error
    1. static class MyStaticClass1 {  
    2.     //your code   
    3. }  
    4. class MyClass2: MyStaticClass1 {  
    5.     //your code   
    6. }  
    Error

    CS0709 'MyClass2': cannot derive from static class 'MyStaticClass1'

Abstract Class

abstract class Student

  1. {  
  2.     public int StudentId {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public string StudentName {  
  7.         get;  
  8.         set;  
  9.     }  
  10.     public abstract void Add();  
  11. }  
Abstract Partial Class
  1. public abstract partial class Student {  
  2.     public static int StudentId {  
  3.         get;  
  4.         set;  
  5.     } = 1;  
  6.     public override string ToString() {  
  7.         return $ "Student Id is {StudentId:0000} and name is {StudentName}";  
  8.     }  
  9. }  
  10. public abstract partial class Student {  
  11.     public static string StudentName {  
  12.         get;  
  13.         set;  
  14.     } = "Banketeshvar Narayan";  
  15. }  
  1. It cannot create an instance of an abstract class i.e. abstract class cannot be instantiated.

    The code snippet, mentioned below will give compile time error
    1. abstract class MyClass {  
    2.     //Your code  
    3. }  
    4. class Program {  
    5.     static void Main(string[] args) {  
    6.         MyClass obj = new MyClass();  
    7.     }  
    8. }  
    Error

    CS0144 Cannot create an instance of the abstract class or interface 'MyClass'

  2. An abstract class can have a non-static constructor and static constructor as well. It can implement an interface and can derive from another class. An abstract class can be a base class also. The sample code image of code snippet for the same is given below.

    C#

Sealed Class

  1. sealed class Student {  
  2.     public int StudentId {  
  3.         get;  
  4.         set;  
  5.     } = 1;  
  6.     public string StudentName {  
  7.         get;  
  8.         set;  
  9.     } = "Banketeshvar Narayan";  
  10.     public override string ToString() {  
  11.         return $ "Student Id is {StudentId:0000} and name is {StudentName}";  
  12.     }  
  13. }  
Sealed Partial Class
  1. public sealed partial class Student {  
  2.     public static int StudentId {  
  3.         get;  
  4.         set;  
  5.     } = 1;  
  6.     public override string ToString() {  
  7.         return $ "Student Id is {StudentId:0000} and name is {StudentName}";  
  8.     }  
  9. }  
  10. public sealed partial class Student {  
  11.     public static string StudentName {  
  12.         get;  
  13.         set;  
  14.     } = "Banketeshvar Narayan";  
  15. }  
Sealed class cannot be further inherited i.e. it cannot be a base class for any type but it can inherit a class and can be a child class. It can be instantiated, can have a static constructor, instance constructor and it can implement an interface also. It can be a partial class.

The pictorial representation of the statement is mentioned below.

C#

If you would like to test the statement written in the pictorial representation, then you can use the code snippet, mentioned below.
  1. namespace SealedClassExamples {  
  2.     interface I { /* your Code */ }  
  3.     public class Human { /*Your code */ }  
  4.     public sealed class Student: Human, I {  
  5.         static Student() { /*Your code */ }  
  6.         public Student() { /*Your code */ }  
  7.     }  
  8.     class MyClass {  
  9.         void DoSomething() {  
  10.             Student st = new Student();  
  11.         }  
  12.     }  
  13.     class A: Student {}  
  14.     public sealed partial class Person {  
  15.         public static string Name => "Banketeshvar Narayan";  
  16.     }  
  17. }  
Concrete Class (Simple Class)
  1. class Student {  
  2.     public int StudentId {  
  3.         get;  
  4.         set;  
  5.     } = 1;  
  6.     public string StudentName {  
  7.         get;  
  8.         set;  
  9.     } = "Banketeshvar Narayan";  
  10.     public override string ToString() {  
  11.         return $ "Student Id is {StudentId:0000} and name is {StudentName}";  
  12.     }  
  13. }  
Partial Concrete Class
  1. public partial class Student {  
  2.     public int StudentId {  
  3.         get;  
  4.         set;  
  5.     } = 1;  
  6.     public override string ToString() {  
  7.         return $ "Student Id is {StudentId:0000} and name is {StudentName}";  
  8.     }  
  9. }  
  10. public partial class Student {  
  11.     public string StudentName {  
  12.         get;  
  13.         set;  
  14.     } = "Banketeshvar Narayan";  
  15. }  
Concrete class or simple class is the class, which does not use any restriction like static, sealed or an abstract class.

Concrete classes can be a base class, child class, can be instantiated, can have a static constructor, can have instance constructor & can implement an interface.

Partial Method in C#
  1. partial class Class1 {  
  2.     partial void DoSomething();  
  3. }  
  4. partial class Class1 {  
  5.     partial void DoSomething() {  
  6.         WriteLine("Hello");  
  7.     }  
  8. }  
We can have partial method in C# but there are some restrictions
  1. Partial method must be declared already before implementing it. 

    If you are going to implement the partial method then defining declaration must be available for the same i.e. partial method must be declared already before implementing it.

    i.e. the code mentioned below will give compile time error.
    1. partial class Class1 {  
    2.     //partial void DoSomething();  
    3. }  
    4. partial class Class1 {  
    5.     partial void DoSomething() {  
    6.         WriteLine("Hello");  
    7.     }  
    8. }  
    Error CS0759 

    No defining declaration is found for implementing the declaration of the partial method 'Class1.DoSomething()'.

    C#

  2. Partial methods must have a void return type. The code mentioned below will give compile time error.
    1. partial class Class1 {  
    2.     partial int Add(int x, int y);  
    3. }  
    4. partial class Class1 {  
    5.     partial int Add(int x, int y) {  
    6.         return x + y;  
    7.     }  
    8. }  
    C#

  3. Accessibility of partial method is private and no access modifier is allowed.
    1. partial class Class1 {  
    2.     public partial void DoSomething();  
    3.     /* Compile Time Error: Error  
    4.      * CS0750 A partial method cannot have access modifiers  
    5.      * or the virtual, abstract, override, new, sealed,  
    6.      * or extern modifiers 
    7.      */  
    8. }  
    9. partial class Class1 {  
    10.     partial void DoSomething() {  
    11.         WriteLine("Hello");  
    12.     }  
    13. }  
    C#
  4. Signature of both the partial methods should be the same.

    The code mentioned below will give compile time error because the signature does not match.
    1. partial class Class1 {  
    2.     partial void Add(int x, int y);  
    3. }  
    4. partial class Class1 {  
    5.     partial void Add(int x, int y, int z) {  
    6.             WriteLine($ "{x + y}");  
    7.         }  
    8.         /* Compilee Error: Error CS0759 No defining declaration found for  
    9.          * implementing declaration of partial method 'Class1.Add(int, int, int)'  
    10.          */  
    11. }  
  5. We can declare a partial method inside the partial class or inside the partial struct.

    That is the type in which I am going to declare a partial method must be partial. The following type can be declared as partial.

    1. Partial Interface
    2. Partial Class
    3. Partial Structure

    So, you can see that we can have partial interface, partial class & partial struct but the partial method can only be written inside Partial struct and Partial class.
    C#

Structure (struct) in C#

In C#, we can create a structure or struct, using the keyword struct. As explained earlier, a struct is a value type and it is directly stored in the stack of the memory.

Create a struct

  1. using static System.Console;  
  2. namespace StructExample {  
  3.     class Program {  
  4.         static void Main(string[] args) {  
  5.             MyCoordinates obj;  
  6.             obj.xCoordinate = 30;  
  7.             obj.yCoordinate = 40;  
  8.             WriteLine($ "{obj.xCoordinate} {obj.yCoordinate}");  
  9.         }  
  10.     }  
  11.     struct MyCoordinates {  
  12.         public int xCoordinate;  
  13.         public int yCoordinate;  
  14.     }  
  15. }  
C#

Enum (enum) in C#

Enum is a value type in C# and the code snippet is mentioned below to explain how to create an enum.
  1. enum RainbowColors {  
  2.     RED = 1,  
  3.         ORANGE = 2,  
  4.         YELLOW = 3,  
  5.         GREEN = 4,  
  6.         BLUE = 5,  
  7.         INDIGO = 6,  
  8.         VIOLET = 7  
  9. }  
Important Questions
  1. We can use foreach loop over the collection, which implements IEnumerable interface but enum does not implement any interface, can we use foreach loop with enum?

    Answer

    Yes, the complete code is mentioned below to demonstrate that how we can use foreach loop over enum
    1. using System;  
    2. namespace EnumExample {  
    3.     class Program {  
    4.         static void Main(string[] args) {  
    5.             foreach(var color in Enum.GetValues(typeof(RainbowColors))) {  
    6.                 Console.WriteLine(color);  
    7.             }  
    8.         }  
    9.     }  
    10.     enum RainbowColors {  
    11.         RED = 1,  
    12.             ORANGE = 2,  
    13.             YELLOW = 3,  
    14.             GREEN = 4,  
    15.             BLUE = 5,  
    16.             INDIGO = 6,  
    17.             VIOLET = 7  
    18.     }  
    19. }  
  2. Can I write a partial enum?

    Answer

    No, if you will try to use the partial keyword with enum, then you will get a compiler error, as shown below.

    Error
    CS0267 “The 'partial' modifier can only appear immediately before 'class', 'struct', 'interface', or 'void'”

Interface

An interface can be created using the keyword ‘interface’ in C#. An interface is a contract and that’s why all the Methods, properties, Indexers, Events which are a part of the interface must be implemented by the class or struct, which implements the interface. An interface can contain only signature of Methods, Properties, Indexers and Events.

Following is an example of an Interface.

  1. interface IInterface {  
  2.     int MyProperty {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     void Display();  
  7. }  
Partial Interface
  1. partial interface I1 {  
  2.     void Method1();  
  3.     void Method2();  
  4. }  
  1. Can an interface implement another interface?

    Answer

    Yes, an Interface can implement another interface.

    Example
    1. interface I1 {  
    2.     void Method1();  
    3.     void Method2();  
    4. }  
    5. interface I2: I1 {  
    6.     void Method3();  
    7.     void Method4();  
    8. }  
  2. Can an interface implement multiple interfaces?

    Answer Yes, an interface can implement multiple interfaces.

    Example
    1. interface I1 {  
    2.     void Method1();  
    3.     void Method2();  
    4. }  
    5. interface I2: I1 {  
    6.     void Method3();  
    7.     void Method4();  
    8. }  
    9. interface I3: I1, I2 {  
    10.     void Method5();  
    11.     void Method6();  
    12. }  
  3. Can an interface have events?

    Answer

    Yes, an Interface can have methods, properties, indexers & events.

  4. Can I use the public keyword with interface members?

    Answer

    No, all the members of the interface are public by default but we cannot use any access modifiers explicitly with the interface members.

  5. Can an interface have constructors?

    Answer

    No, Interfaces cannot contain constructors.

  6. Can I use the static keyword with the interface method?

    Answer

    No, we cannot use static and public modifiers with the interface method.

Access Modifiers in C#

C#

What are the access modifiers allowed with Class?

  1. Class  
  2. public & internal(  
  3.     default) only.  
  4. Class Members  
  5. We can use all the 5 access modifier i.e.private(  
  6.     default), protected, internal, protected internal and public.  
  7. public class User {}  
  8. Or  
  9. class User1 {}  
  10. Or  
  11. internal class User2 {}  
Class Members with all the 5 access modifiers
  1. public class User {  
  2.     //private access modifiers  
  3.     private int UserId {  
  4.         get;  
  5.         set;  
  6.     } = 1;  
  7.     //protected access modifiers  
  8.     protected string UserName {  
  9.         get;  
  10.         set;  
  11.     } = "Banketeshvar Narayan";  
  12.     ////internal access modifiers  
  13.     internal string EmailId {  
  14.         get;  
  15.         set;  
  16.     } = "[email protected]";  
  17.     //protected internal access modifiers  
  18.     protected internal string City {  
  19.         get;  
  20.         set;  
  21.     } = "Delhi";  
  22.     //public access modifiers  
  23.     public string Country {  
  24.         get;  
  25.         set;  
  26.     } = "India";  
  27. }  
Note

The elements defined in a namespace cannot be explicitly declared as private, protected or protected internally.

What are the access modifiers allowed with enum?

Enum
default access modifier is internal and we can use public & internal explicitly.

Enum Fields
No access modifier is allowed with enum fields and default member accessibility is public.
  1. enum IndianTricolor {  
  2.     Saffron = 1,  
  3.         White = 2,  
  4.         Green = 3  
  5. }  
internal enum IndianTricolor is shown below.
  1. {  
  2.     Saffron = 1,  
  3.         White = 2,  
  4.         Green = 3  
  5. }  
Or
  1. public enum IndianTricolor {  
  2.     Saffron = 1,  
  3.         White = 2,  
  4.         Green = 3  
  5. }  
What are the access modifiers allowed with an interface?

Interface
  1. public & internal(  
  2.     default) only.  
  3. interface IUser1 {}  

  4. internal interface IUser1 {}  
  5.   
  6. public interface IUser1 {}  
Interface Members
No access modifier is allowed with the interface members and default member accessibility is public.

What are the access modifiers allowed with the struct?

Struct
public & internal (default) only.

Struct Members
Private, public and internal access modifiers are allowed with struct members and the default member accessibility is private.
  1. public / internal(  
  2.     default access modifier) struct MyStruct {  
  3.     private(  
  4.         default access modifier) / internal / protected int MyProperty {  
  5.         get;  
  6.         set;  
  7.     }  
  8. }  
Tips

Generally, most of the developers start remembering things rather than understanding the actual structure and behavior but it is not good for the developers.

If you look at the access modifier for the class, then you will notice that the default access modifier for the class is internal whereas default access modifier for a property is private, so I am going to give you four tips, which help you to understand allowed access modifiers and their behavior.
  1. The elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal. Thus, we can only use internal and public access modifiers with the class, interface, enum & struct.
  2. Class members can use all the 5 access modifiers where struct members cannot use access modifiers “protected” and “protected internal” because struct cannot be inherited.
  3. The default access modifier is "the most restricted access modifier you could declare for that member". Thus, default access for the class, interface, enum & struct is “internal” for enum & interface member default is public and for class and struct member; it’s private.
  4. If the members of a type can have only public accessibility, then we cannot use any access modifiers explicitly and it will always have public accessibility implicitly. Thus, interface and enum members cannot have access modifiers explicitly.

What is the use of ‘typeof’ keyword in C#?

It is used to get the types and using this, we can do a lot of things of reflection without using complex logic and a few examples are shown below.

  1. Type t = typeof(User);  
  2. WriteLine(t.Assembly);  
  3. WriteLine(t.AssemblyQualifiedName);  
  4. WriteLine(t.IsAbstract);  
  5. WriteLine(t.IsSealed);  
  6. WriteLine(t.IsArray);  
  7. WriteLine(t.IsClass);  
  8. WriteLine(t.IsVisible);  
  9. WriteLine(t.IsValueType);  
  10. WriteLine(t.IsInterface);  
How to Implement and call the same methods of interfaces and base class?

Condition 1
I have 2 interfaces, where both are having the same method and I would like to implement it the same class how it will be implemented 
i.e. have the code, as shown below.
  1. interface IInterface1 {  
  2.     void Display();  
  3. }  
  4. interface IInterface2 {  
  5.     void Display();  
  6. }  
Now, I am going to implement it in the same class. Following is the code snippet.
  1. class A: IInterface1, IInterface2 {  
  2.     public void Display() {  
  3.         WriteLine("Display method of class A");  
  4.     }  
  5. }  
  6. Then calling it using the below code  
  7. A objA = new A();  
  8. IInterface1 objB = new A();  
  9. IInterface2 objC = new A();  
  10. objA.Display();  
  11. objB.Display();  
  12. objC.Display();  
Output

Display method of class A
Display method of class A
Display method of class A

In the code mentioned above, you can see that I have implemented only 1 Display() method. Thus, if we are going to use more than one interface and they are having the same method name then it is not necessary to implement all those methods explicitly but in this case, all the instances will point to the same method, as you can see in the example, mentioned above.

Condition 2
Now, I am going to Add 1 parameter to differentiate Interface methods.
  1. interface IInterface1 {  
  2.     void Display();  
  3. }  
  4. interface IInterface2 {  
  5.     void Display(int x);  
  6. }  
  7. class A: IInterface1, IInterface2 {  
  8.     public void Display() {  
  9.         WriteLine("Display method of class A");  
  10.     }  
  11.     public void Display(int x) {  
  12.         WriteLine($ "Display method {x:0000}");  
  13.     }  
  14. }  
  15. class Program {  
  16.     static void Main(string[] args) {  
  17.         A objA = new A();  
  18.         IInterface1 objB = new A();  
  19.         IInterface2 objC = new A();  
  20.         objA.Display();  
  21.         objB.Display();  
  22.         objC.Display(50);  
  23.     }  
  24. }  
Output

Display method of class A
Display method of class A
Display method 0050

Thus, you can see that still there is no issue and everything is working fine.

Condition 3
Now, let’s say Display() method in both the interfaces are having 0 parameters and I want to implement it separately, then I will implement it like the following code snippet.
  1. class A: IInterface1, IInterface2 {  
  2.     void IInterface1.Display() {  
  3.         WriteLine("Display method of IInterface1");  
  4.     }  
  5.     void IInterface2.Display() {  
  6.         WriteLine("Display method of IInterface2");  
  7.     }  
  8. }  
If you look at the code mentioned above, you will notice 2 things.
  1. I have used an interface name with the method name to implement it explicitly. This is known as “Implement Interface explicitly”.
  2. I have removed public access modifier because it will not allow any access modifiers. Do you know why it will not allow access modifier? Because now it is explicit implementation and behaving as an interface member.

Condition 4
What is the difference between the following 2 code snippets?

Code Snippet1

  1. interface IInterface1 {  
  2.     void Display();  
  3. }  
  4. class A: IInterface1 {  
  5.     void IInterface1.Display() {  
  6.         WriteLine("Display method of IInterface1");  
  7.     }  
  8. }  
Code Snippet2
  1. interface IInterface1 {  
  2.     void Display();  
  3. }  
  4. class A: IInterface1 {  
  5.     public void Display() {  
  6.         WriteLine("Display method of IInterface1");  
  7.     }  
  8. }  
You can see that in “Code Snippet 1”, I have implemented the interface method explicitly, whereas in “Code Snippet 2” an interface method has been implemented implicitly.

You can call the implicitly implemented method of an interface by creating an object of the class, which implements it without the interface reference.

i.e. the code snippet, mentioned below will be compiled and will give the same output while being called by objA or objB.
  1. interface IInterface1 {  
  2.     void Display();  
  3. }  
  4. class A: IInterface1 {  
  5.     public void Display() {  
  6.         WriteLine("Display method of IInterface1");  
  7.     }  
  8. }  
  9. A objA = new A();  
  10. IInterface1 objB = new A();  
  11. objA.Display();  
  12. objB.Display();  
The code snippet, mentioned below will not be compiled.
  1. interface IInterface1 {  
  2.     void Display();  
  3. }  
  4. class A: IInterface1 {  
  5.     void IInterface1.Display() {  
  6.         WriteLine("Display method of IInterface1");  
  7.     }  
  8. }  
  9. A objA = new A();  
  10. IInterface1 objB = new A();  
  11. objA.Display();  
  12. objB.Display();  
Error 
'A' does not contain a definition for 'Display' and no extension method 'Display' accepts a first argument of type 'A' could be found (are you missing a using directive or an assembly reference?)

You may be wondering why it is giving the compile time error. The reason for compile time error is the Display() method is having implementation inside class A but it is explicitly mentioned that it is only member of “IInterface1”.

Now I am going put one more condition in front of you and let’s try to understand the code snippet, mentioned below.

Condition 5
A class is having a base class and is also implementing two other interfaces and the types, which have the same method name.
  1. interface IInterface1 {  
  2.     void Display();  
  3. }  
  4. interface IInterface2 {  
  5.     void Display();  
  6. }  
  7. class B {  
  8.     public void Display() {  
  9.         WriteLine("Display method of class B");  
  10.     }  
  11. }  
  12. A objA = new A();  
  13. IInterface1 objB = new A();  
  14. IInterface2 objC = new A();  
  15. objA.Display();  
  16. objB.Display();  
  17. objC.Display();  
Output

Display method of class B
Display method of IInterface1
Display method of IInterface2

Condition 6
  1. class A: B, IInterface1, IInterface2 {  
  2.     public void Display() {  
  3.         WriteLine("Display method written inside A");  
  4.     }  
  5. }  
  6. A objA = new A();  
  7. objA.Display();  
It will call method of Class A and will not call its parent class method.

If you want to call parent class method, then you have to give reference to the parent class method.
i.e.
B objD = new B(); objD.Display();

After going through all these 6 different conditions, I hope that if an interviewer is trying to complicate the situation of implicit and explicit method implementation to any level, you will not be confused and you will be able to answer it confidently.

How to call multiple constructors of a class with single object creation?

C#

In the example mentioned below, I have a class “A”, which is having 4 instance constructors. The first constructor is a Parameterless constructor and the second constructor is having one parameter, the third constructor is having two parameters and the fourth constructor is having three parameters.
  1. class A {  
  2.     public A() {  
  3.         WriteLine("Parameterless constructor called");  
  4.     }  
  5.     public A(int x) {  
  6.         WriteLine("constructor with 1 parameter called");  
  7.     }  
  8.     public A(int x, int y) {  
  9.         WriteLine("constructor with 2 parameters called");  
  10.     }  
  11.     public A(int x, int y, int z) {  
  12.         WriteLine("constructor with 3 parameters called");  
  13.     }  
  14. }  
Now, I would like to call all those 4 constructors by just creating only one object. Let’s see, how can it be done? The new code will be, as shown below.
  1. class A {  
  2.     public A(): this(0) {  
  3.         WriteLine("Parameterless constructor called");  
  4.     }  
  5.     public A(int x): this(x, 0) {  
  6.         WriteLine("constructor with 1 parameter called");  
  7.     }  
  8.     public A(int x, int y): this(x, y, 0) {  
  9.         WriteLine("constructor with 2 parameters called");  
  10.     }  
  11.     public A(int x, int y, int z) {  
  12.         WriteLine("constructor with 3 parameters called");  
  13.     }  
  14. }  
  15. A a = new A(); //or // A a = new A { };  
And output will be

constructor with 3 parameters called
constructor with 2 parameters called
constructor with 1 parameter called
Parameterless constructor called

I am going to ask you few questions of C# code snippet output, which are very popular and can be asked to anyone. So, let’s continue with the code snippets, mentioned below.

What will be the output of below code Snippet?
  1. using static System.Console;  
  2. namespace Example1 {  
  3.     class A {  
  4.         public void Display() {  
  5.             WriteLine($ "Class A");  
  6.         }  
  7.     }  
  8.     class B: A {  
  9.         public void Display() {  
  10.             WriteLine($ "Class B");  
  11.         }  
  12.     }  
  13.     class Program {  
  14.         static void Main(string[] args) {  
  15.             A obj1 = new A();  
  16.             A obj2 = new B();  
  17.             B obj3 = new B();  
  18.             obj1.Display();  
  19.             obj2.Display();  
  20.             obj3.Display();  
  21.         }  
  22.     }  
  23. }  
Output

Class A
Class A
Class B

What will be the output of the code snippet, mentioned below, if I create different types of objects in different ways?
  1. class A {  
  2.     public void Display() {  
  3.         WriteLine($ "Class A");  
  4.     }  
  5. }  
  6. class B: A {  
  7.     public void Display() {  
  8.         WriteLine($ "Class B");  
  9.     }  
  10. }  
  11. class C: A {  
  12.     public static void Display() {  
  13.         WriteLine($ "Class C");  
  14.     }  
  15. }  
  16. class D: A {  
  17.     public virtual void Display() {  
  18.         WriteLine($ "Class D");  
  19.     }  
  20. }  
  21. class E: A {  
  22.     public virtual new void Display() {  
  23.         WriteLine($ "Class E");  
  24.     }  
  25. }  
  26. abstract class F: A {  
  27.     public abstract void Display();  
  28. }  
  29. abstract class G: A {  
  30.     public abstract new void Display();  
  31. }  
  32. abstract class H: A {  
  33.     public abstract void Display(int x);  
  34. }  
I am not going to write the output of the code snippet, mentioned above rather I am leaving this as an exercise for the developers whose OOPS is not strong, so they can execute all the scenarios, mentioned above with the different combinations and can understand basics of OOPS. If anybody thinks that he needs an output of the code snippet, mentioned below then I will put it in the comment section of this article later on. I am also going to give some tips specifically compiler error messages for the preceding code snippet so that you can understand it in a better way.

Tips (compiler error messages)
  1. A static member cannot be marked as an override, virtual or abstract.
  2. It cannot be declared as the instance members in a static class.
  3. An object reference is required for the non-static field, method or property.
  4. An abstract class cannot be sealed or static. A class cannot be both static and sealed.
  5. The 'partial' modifier can only appear immediately before 'class', 'struct', 'interface' or 'void'.
  6. Elements defined in a namespace cannot be explicitly declared as private, protected or protected internally.

What is the use of 'extern' keyword in C#?

We use 'extern' keyword with a method to indicate that the method has been implemented externally i.e. out of your current C# code. Below is a code sample from MSDN, which describes the use of extern

[DllImport("User32.dll")]
public static extern int MessageBox(int h, string m, string c, int type);

NOTE

While using [DllImport("User32.dll")], you need to include the namespace System.Runtime.InteropServices;

for complete details about extern visit here.

Sequence of Modifiers and other attributes with class and method

In the case of C# sometimes sequence of modifiers matters and you should be aware of that if you are going for an interview.

e.g. public abstract partial class Student or public partial abstract class Student

You would be wondering why I am explaining microlevel questions? I am explaining it because in some cases, you have to face such questions and you will feel a bit irritated or upset if you are not aware of all those things.

Sometimes sequence matters and sometimes it doesn’t matter but we should keep some best practices in mind so that we write an error free code.

Class

[modifiers] [partial] className [:] [inheritance list]

Method

[modifiers] [partial] returnType methodName([parameters])
Method Modifiers List.

  • new
  • internal
  • private
  • protected
  • public
  • abstract
  • async
  • extern
  • override
  • sealed
  • static
  • virtual
There are some more modifiers, which I have not mentioned here because they are used rarely.

Usage of ref keyword in C#

When we pass a value type variable as a parameter, then it passes its value as a parameter i.e. making a copy of the data. Making any changes inside the method in which it has been passed as a parameter will not affect the variable accessed outside the method. Because it is passed as a value and whatever the changes will be made inside the local method will be done on a copy of that variable.

If we need to change the value type variable from inside the method in which it has been passed as a parameter, then you can pass this value type variable as the reference, using the ‘ref’ keyword. In this case, the reference of value type will be passed as a parameter rather than the value of the variable.

Let’s consider about the reference type

A variable of the reference type contains the reference to its data and does not contain data directly. Whenever we pass a reference type variable as a parameter, then the data is not passed but the reference of the variable is passed inside the method i.e. passes the value of memory address not the value of data and that’s why, if I make any change to this variable inside the method, then it will be available outside the method but it is only limited to the modification and if I am going to allocate a new memory and modifying the variable, then these changes will not be reflected outside the method.

If I need that the changes be done inside the method for the variable by allocating new memory it should be reflected outside the method in that case, we need to pass the parameter of reference type with ‘ref’ keyword. If I pass a reference type variable parameter using ‘ref’ keyword, then the reference of the memory address is itself passed as reference and so allocating a new memory will also be available outside the method.

Below is the pictorial representation of the same thing stated above.

There are four combinations of passing the parameter inside a method. There are a lot of other options to pass a parameter as value but I am not going to discuss it here otherwise it will create confusion. I will discuss other parameter passing options in a separate section.
  1. Passing Value type variable without ‘ref’ keyword.
  2. Passing Value type variable with ‘ref’ keyword.
  3. Passing reference type variable without ‘ref’ keyword.
  4. Passing reference type variable with ‘ref’ keyword.

Passing Value type variable without ‘ref’ keyword
C#

In the case mentioned above, the variable x is having an initial value 20 and its value i.e. 20 is passed as a parameter for the method Modify. Inside the method modify it has been modified and added 50 to its previous value so it becomes 70 but the value of the variable ‘x’ outside the Modify() method is still 20 because it has modified its value not the reference.

Below is the complete code

  1. using static System.Console;  
  2. namespace PassingValueTypeWithoutRef {  
  3.     class Program {  
  4.         static void Main(string[] args) {  
  5.             Program p = new Program();  
  6.             int x = 20;  
  7.             p.Modify(x);  
  8.             WriteLine(x);  
  9.         }  
  10.         public void Modify(int x) {  
  11.             x += 50;  
  12.             WriteLine(x);  
  13.         }  
  14.     }  
  15. }  
Passing Value type variable with ‘ref’ keyword

C#

In the case mentioned above, the variable x is having an initial value 20 and its reference passed as a parameter for the method Modify. Inside the method modify it has been modified and added 50 to its previous value so it becomes 70. As this variable has been passed as reference i.e. value of its address has been passed instead of data so the value of the variable ‘x’ outside the Modify method is also updated and you will get 70 everywhere.

Below is the complete code
  1. using static System.Console;  
  2. namespace PassingValueTypeWithRef {  
  3.     class Program {  
  4.         static void Main(string[] args) {  
  5.             Program p = new Program();  
  6.             int x = 20;  
  7.             p.Modify(x);  
  8.             WriteLine(x);  
  9.         }  
  10.         public void Modify(int x) {  
  11.             x += 50;  
  12.             WriteLine(x);  
  13.         }  
  14.     }  
  15. }  
Passing reference type variable without ‘ref’ keyword

In C#, whatever we passed inside the method as a parameter is always passed as the value. So, that happens when we pass value type then copy of a value typed is passed, whereas in the case of reference type variable its reference address is passed as a method parameter.

C#

In the example mentioned above, you can see that when I am passing a reference type as a parameter then its address is being passed as data not the actual data. Due to this, if I change the user object from the ModifyUser() method, then it is being reflected outside but If I allocate a new memory and then make any change; it will not be reflected outside the method.

Complete Code
  1. using static System.Console;  
  2. namespace PassingReferenceTypeWithoutRef {  
  3.     class Program {  
  4.         static void Main(string[] args) {  
  5.             User user = new User {  
  6.                 UserId = 101  
  7.             };  
  8.             ModifyUser(user);  
  9.             WriteLine($ "User id: {user.UserId} & user name: {user.UserName}");  
  10.         }  
  11.         public static void ModifyUser(User user) {  
  12.             user.UserName = "Banketeshvar Narayan";  
  13.             user = new User {  
  14.                 UserId = 102,  
  15.                     UserName = "Manish Sharma"  
  16.             };  
  17.             WriteLine($ "User id: {user.UserId} & user name: {user.UserName}");  
  18.         }  
  19.     }  
  20.     class User {  
  21.         public int UserId {  
  22.             get;  
  23.             set;  
  24.         }  
  25.         public string UserName {  
  26.             get;  
  27.             set;  
  28.         }  
  29.     }  
  30. }  
Passing reference type variable with ‘ref’ keyword
C#

In the example mentioned above, you can see that when I am passing a reference type as a parameter, then its address is being passed as the data and not the actual data. Due to this, if I change the user object from the ModifyUser() method, then it is being reflected outside, even if I allocate a new memory and then make any change; it will be reflected outside the method.

Complete Code
  1. using static System.Console;  
  2. namespace PassingReferenceTypeWithRef {  
  3.     class Program {  
  4.         static void Main(string[] args) {  
  5.             User user = new User {  
  6.                 UserId = 101  
  7.             };  
  8.             ModifyUser(ref user);  
  9.             WriteLine($ "User id: {user.UserId} & user name: {user.UserName}");  
  10.         }  
  11.         public static void ModifyUser(ref User user) {  
  12.             user.UserName = "Banketeshvar Narayan";  
  13.             user = new User {  
  14.                 UserId = 102,  
  15.                     UserName = "Manish Sharma"  
  16.             };  
  17.             WriteLine($ "User id: {user.UserId} & user name: {user.UserName}");  
  18.         }  
  19.     }  
  20.     class User {  
  21.         public int UserId {  
  22.             get;  
  23.             set;  
  24.         }  
  25.         public string UserName {  
  26.             get;  
  27.             set;  
  28.         }  
  29.     }  
  30. }  
Passing string variable without ‘ref’ keyword

The String is the reference type but sometimes it behaves like the value type. Even though in the current scenario, if I pass the string inside a method and modify it, then it will not be affected to the outside variable from where the method has been called. For the code snippet mentioned below, an output will not be the same.
  1. class Program {  
  2.     static void Main(string[] args) {  
  3.         string name = "B Narayan";  
  4.         ModifyName(name);  
  5.         WriteLine($ "name is : {name}");  
  6.         //output: name is : B Narayan  
  7.     }  
  8.     public static void ModifyName(string name) {  
  9.         name = "Manish Sharma";  
  10.         WriteLine($ "name is : {name}");  
  11.         //output: name is : Manish Sharma  
  12.     }  
  13. }  
As you can see the string modified inside the method is not affecting the outside variable, so if we need to modify outer variable from ModifyName() method, then we have to pass the string parameter with ref keyword.

Passing string variable with ‘ref’ keyword
  1. class Program {  
  2.     static void Main(string[] args) {  
  3.         string name = "B Narayan";  
  4.         ModifyName(ref name);  
  5.         WriteLine($ "name is : {name}");  
  6.         //output: name is : Manish Sharma  
  7.     }  
  8.     public static void ModifyName(ref string name) {  
  9.         name = "Manish Sharma";  
  10.         WriteLine($ "name is : {name}");  
  11.         //output: name is : Manish Sharma  
  12.     }  
  13. }  
Now, you can see that I have passed the string variable name with ref keyword, so it has been modified on both the places.

Usage of ‘out’ keyword in C#

We can use ‘out’ keyword with the parameter and it behaves very similar to the parameter passed with ‘ref’ keyword but any argument passed as out parameter need not be initialized whereas in the case of 'ref', it must be initialized. Another difference is that ref parameter may be assigned inside the method in which it is called (not necessary), but in the case of “out” it must be assigned in the calling method before any exit.

C#
Using ‘params’ in method parameter

The ‘params’ keyword can be used to specify a method parameter that takes a variable number of arguments. When we use ‘params’ keyword to pass the variable number of arguments, we can send any number of arguments or no arguments but all the arguments passed should be of the same type.

A method can have the only parameter with ‘params’ keyword or with additional parameters and ‘params’ as last parameters but no other parameters can be passed after ‘params’. Let’s try to understand with some examples.

Example 1
  1. static void Main(string[] args) {  
  2.     string my1stLine = "This is my first Line";  
  3.     string my2ndLine = "This is my second Line";  
  4.     string my3rdline = "This is my Third Line";  
  5.     string my4thline = "This is my fourth Line";  
  6.     Print(my1stLine, my2ndLine, my3rdline, my4thline);  
  7. }  
  8. public static void Print(params string[] listToPrint) {  
  9.     foreach(var item in listToPrint) {  
  10.         WriteLine(item);  
  11.     }  
  12. }  
Example 2
  1. static void Main(string[] args) {  
  2.     int userId = 1001;  
  3.     string email1 = "[email protected]";  
  4.     string email2 = "[email protected]";  
  5.     string email3 = "[email protected]";  
  6.     string email4 = "[email protected]";  
  7.     UserDetails(userId, email1, email2, email3, email4);  
  8. }  
  9. public static void UserDetails(int UseId, params string[] emailIds) {  
  10.     foreach(var email in emailIds) {  
  11.         WriteLine($ "userId is {UseId} and emailId is {email}");  
  12.     }  
  13. }  
Example 3
  1. public static void UserDetails(params string[] emailIds, int UseId) {  
  2.     foreach(var email in emailIds) {  
  3.         WriteLine($ "userId is {UseId} and emailId is {email}");  
  4.     }  
  5. }  
Out of the three examples, mentioned above- Example1 & Example 2 will compile & run successfully but the third example will not be compiled. It will give the errors, as shown below.

Error

A params parameter must be the last parameter in a formal parameter list

So far, I have discussed a lot about the method and I would like to mention one last thing, where we can also pass dynamic parameters in the method.
  1. class Program {  
  2.     static void MyDynamicMethod(dynamic dynamicparam) {  
  3.         dynamicparam.DoSomethingDynamic(); // Called dynamically   
  4.     }  
  5.     static void Main(string[] args) {  
  6.         MyDynamicMethod("dynamicValue");  
  7.     }  
  8. }  
This article has become very long already, so I am not going to tell you more about dynamic types but hopefully in the next article of this series, I will discuss it in more depth.

For C# basics concepts, you can refer to the articles written by me. Following is the list for the same.

Different Types of Method Parameters in C#
Break Vs Continue in C#
Understanding Delegates in C#
Understanding Delegates in C# - Part 2
Parallel.ForEach() Vs foreach() Loop in C#

Up Next
    Ebook Download
    View all
    Learn
    View all