C#

C# Interview Questions

Here are top C# interview questions and answers. These C# interview questions are for both beginners and professional C# developers. We will add more questions time by time.

What is C#?

C# (pronounced “C-sharp”) is an object-oriented programming language from Microsoft that aims to combine the computing power of C++ with the programming ease of Visual Basic. C# is based on C++ and contains features similar to those of Java.
C# is designed to work with Microsoft’s .Net platform. Microsoft’s aim is to facilitate the exchange of information and services over the Web, and to enable developers to build highly portable applications.

C# with the help of Visual Studio IDE provides a rapid application development. C# is a modern, object-oriented, simple, versatile, and performance-oriented programming language. C# is developed based on the best features and use cases of several programming languages including C++, Java, Pascal, and SmallTalk.

C# simplifies programming through its use of Extensible Markup Language (XML) and Simple Object Access Protocol (SOAP) which allow access to a programming object or method without requiring the programmer to write additional code for each step. Because programmers can build on existing code, rather than repeatedly duplicating it, C# is expected to make it faster and less expensive to get new products and services to market.

What is an object in C#?

The terms class and object describe the type of objects, and the instances of classes, respectively. So, the act of creating an object is called instantiation. Using the blueprint analogy, a class is a blueprint, and an object is a building made from that blueprint.

Objects are the basic run-time entities of an object oriented system. They may represent a person, a place or any item that the program must handle.

“An object is a software bundle of related variable and methods.” “An object is an instance of a class”

A class will not occupy any memory space. Hence to work with the data represented by the class you must create a variable for the class, that is called an object.

When an object is created using the new operator, memory is allocated for the class in the heap, the object is called an instance and its starting address will be stored in the object in stack memory. An object is created without the new operator, memory will not be allocated in the heap, in other words an instance will not be created and the object in the stack contains the value null. When an object contains null, then it is not possible to access the members of the class using that object.

What is Managed or Unmanaged Code?

Unmanaged Code
  • Applications that are not under the control of the CLR are unmanaged
  • The unsafe code or the unmanaged code is a code block that uses a pointer variable.
  • The unsafe modifier allows pointer usage in unmanaged code.
Managed Code

Managed code is a code whose execution is managed by Common Language Runtime. It gets the managed code and compiles it into machine code. After that, the code is executed.The runtime here i.e. CLR provides automatic memory management, type safety, etc.

Managed code is written in high-level languages run on top of .NET. This can be C#, F#, etc. A code compiled in any of this language with their compilers, a machine code is not generated. However, you will get the Intermediate Language code, compiled and executed by runtime.

Can multiple catch blocks be executed?

In C#, You can use more than one catch block with the try block. Generally, multiple catch block is used to handle different types of exceptions means each catch block is used to handle different type of exception. If you use multiple catch blocks for the same type of exception, then it will give you a compile-time error because C# does not allow you to use multiple catch block for the same type of exception. A catch block is always preceded by the try block.

In general, the catch block is checked within the order in which they have occurred in the program. If the given type of exception is matched with the first catch block, then first catch block executes and the remaining of the catch blocks are ignored. And if the starting catch block is not suitable for the exception type, then compiler search for the next catch block.

try
{

}
catch (IOException ex1)
{
    // Code Block 1
}
catch (Exception ex2)
{
    // Code Block 2
}

In above example if exception is IOException then Code Block 1 will be executed otherwise for other exceptions Code Block 2 will be executed.

What is Boxing and Unboxing in C#?

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the common language runtime (CLR) boxes a value type, it wraps the value inside a System.Object instance and stores it on the managed heap.

This example converts an integer variable i to an object o by using boxing. Then, the value stored in the variable i is changed from 123 to 456. The example shows that the original value type and the boxed object use separate memory locations, and therefore can store different values.

class TestBoxing
{
    static void Main()
    {
        int i = 123;

        // Boxing copies the value of i into object o.
        object o = i;

        // Change the value of i.
        i = 456;

        // The change in i doesn't affect the value stored in o.
        System.Console.WriteLine("The value-type value = {0}", i);
        System.Console.WriteLine("The object-type value = {0}", o);
    }
}
/* Output:
    The value-type value = 456
    The object-type value = 123
*/

Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit. The concept of boxing and unboxing underlies the C# unified view of the type system in which a value of any type can be treated as an object.

// C# implementation to demonstrate 
// the Unboxing 
using System; 
class GFG { 

	// Main Method 
	static public void Main() 
	{ 

		// assigned int value 
		// 23 to num 
		int num = 23; 

		// boxing 
		object obj = num; 

		// unboxing 
		int i = (int)obj; 

		// Display result 
		Console.WriteLine("Value of ob object is : " + obj); 
		Console.WriteLine("Value of i is : " + i); 
	} 
} 

What is the difference between public, static, and void?

Public, Static and Void comes under different categories. Public is the access specifier, static is a keyword and void comes under return type. let me explain one by one:

Public: Whenever a method, class or a class member declared with public access specifier. it means that the member can be access from any where. There is no restriction on accessing the public member.

  • If a class is declared us Public we can access the class wherever we want.
  • if a member of the class is public then we can access the member from anywhere there wont be any restriction on this but class has it restriction if the class isn’t declared public.

Static keyword is used to mention that the static member value won’t change in anytime). throughout the application cycle static member gives same value with referring same memory location.

  • if a variable is declared with static keyword and assigned so some value. While executing a memory blocks get assigned to the static variable. We can able to access the static members without any instance. We can access the member from any where in the application it will same value referring to same memory location.

Void keyword is used in the return type. which actually stating that the method with void return type wont return anything (it returns nothing. don’t think nothing as null because null is a value).

What is Jagged Arrays?

Jagged Array is an array whose elements are arrays with different dimensions and sizes. Sometimes a jagged array called an “array of arrays” and it can store arrays instead of a particular data type value.

// Jagged Array with Single Dimensional Array
int[][] jarray = new int[2][];

// Jagged Array with Two Dimensional Array
int[][,] jarray1 = new int[3][,];

With jagged arrays, we can store (efficiently) many rows of varying lengths. No space (on the tops of the skyscrapers) is wasted. Any type of data—reference or value—can be used.

using System;

class Program
{
    static void Main()
    {
        // Part 1: declare local jagged array with 3 rows.
        int[][] jagged = new int[3][];

        // Part 2: create a new array in the jagged array.
        jagged[0] = new int[2];
        jagged[0][0] = 1;
        jagged[0][1] = 2;
        jagged[1] = new int[1];
        jagged[2] = new int[3] { 3, 4, 5 };

        // Part 3: iterate overall the elements.
        for (int i = 0; i < jagged.Length; i++)
        {
            // Part 4: iterate over the inner array.
            // ... Print all its elements.
            int[] innerArray = jagged[i];
            for (int a = 0; a < innerArray.Length; a++)
            {
                Console.Write(innerArray[a] + " ");
            }
            Console.WriteLine();
        }
    }
}

Output

1 2
0
3 4 5

Can I declare properties in interface?

In C#, a class or a struct can implement one or more interfaces. In C#, an interface can be defined using the interface keyword. Interfaces can contain methods, properties, indexers, and events as members. … An interface can only contain declarations but not implementations.

Interfaces are contracts to be fulfilled by implementing classes. Hence they can consist of public methods, properties and events (indexers are permitted too).

Variables in Interfaces – NO. Can you elaborate on why you need them? You can have variables in Base classes though.
Properties in Interfaces – Yes, since they are paired methods under the hood.
Members of an interface are implicitly public. You cannot specify access modifiers explicitly

What is use of getter & setter?

Getters and Setters are used to effectively protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Getters and setters are also known as accessors and mutators, respectively.

By convention, getters start with get, followed by the variable name, with the first letter of the variable name capitalized. Setters start with set, followed by the variable name, with the first letter of the variable name capitalized.

public class Vehicle {
  private String color;
  
  // Getter
  public String getColor() {
  return color;
  }
  
  // Setter
  public void setColor(String c) {
  this.color = c;
  }
}

The getter method returns the value of the attribute. The setter method takes a parameter and assigns it to the attribute.

public stativ void main(String[] args) {
  Vehicle v1 = new Vehicle();
  v1.setColor("Red");
  System.out.println(v1.getColor());
}

// Outputs "Red"

Getters and setters allow control over the values. You may validate the given value in the setter before actually setting the value.

How can we restrict class to instantiate?

  • We declare a class as abstract to prevent us from creating an object of the class
  • If you try to create an instance of a static class then it also prompts you with an error after implementation of the code
  • If we declare a private or protected constructor then it also prevents us from creating an instance of the class

Define Constructors.

In C#, constructor is a special method which is invoked automatically at the time of object creation. It is used to initialize the data members of new object generally. The constructor in C# has the same name as class or struct.

There are different types of constructors in C#.

  • Default Constructor
  • Parameterized Constructor
  • Copy Constructor
  • Static Constructor
  • Private Constructor

In case, if we create a class without having any constructor, then the compiler will automatically create a one default constructor for that class. So, there is always one constructor that will exist in every class.
In c#, a class can contain more than one constructor with different types of arguments and the constructors will never return anything, so we don’t need to use any return type, not even void while defining the constructor method in the class.

public class User
{
// Constructor
public User()
{
// Your Custom Code
}
}

What is the difference between ref & out parameters?

Ref and out parameters are used to pass an argument within a method.

Ref

The ref keyword is used to pass an argument as a reference. This means that when value of that parameter is changed in the method, it gets reflected in the calling method. An argument that is passed using a ref keyword must be initialized in the calling method before it is passed to the called method.

Out

The out keyword is also used to pass an argument like ref keyword, but the argument can be passed without assigning any value to it. An argument that is passed using an out keyword must be initialized in the called method before it returns back to calling method.

public class Example
{
 public static void Main() //calling method
 {
 int val1 = 0; //must be initialized 
 int val2; //optional

 Example1(ref val1);
 Console.WriteLine(val1); // val1=1

 Example2(out val2);
 Console.WriteLine(val2); // val2=2
 }

 static void Example1(ref int value) //called method
 {
 value = 1;
 }
 static void Example2(out int value) //called method
 {
 value = 2; //must be initialized 
 }
}

/* Output
 1
 2
 */

What is the difference between a struct and a class in C#?

A class is a user-defined blueprint or prototype from which objects are created. Basically, a class combines the fields and methods(member function which defines actions) into a single unit.

A structure is a collection of variables of different data types under a single unit. It is almost similar to a class because both are user-defined data types and both hold a bunch of different data types.

S.N Struct Classes
 1 Structs are value types, allocated either on the stack or inline in containing types.Classes are reference types, allocated on the heap and garbage-collected. 
 2  Allocations and de-allocations of value types are in general cheaper than allocations and de-allocations of reference types. Assignments of large reference types are cheaper than assignments of large value types.
 3In structs, each variable contains its own copy of the data (except in the case of the ref and out parameter variables), and an operation on one variable does not affect another variable.
 In classes, two variables can contain the reference of the same object and any operation on one variable can affect another variable.

What would happen when we define private constructor?

The use of private constructor is to serve singleton classes. … Using private constructor we can ensure that no more than one object can be created at a time. By providing a private constructor you prevent class instances from being created in any place other than this very class.

What is the use of ‘using’ statement in C#?

The using statement is mostly used when you need to one or more resources in a segment. The using statement obtains one or various resources, executes them and then releases the objects or resources. It is widely used in database connectivity through C#.

When you are using an object that encapsulates any resource, you have to make sure that when you are done with the object, the object’s Dispose method is called. This can be done more easily using the using statement in C#. The using statement simplifies the code that you have to write to create and then finally clean up the object. The using statement obtains the resource specified, executes the statements and finally calls the Dispose method of the object to clean up the object.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Using_Statement
{
    class check_using : IDisposable
    {
        public void Dispose()
        {
            Console.WriteLine("Execute  Second");
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            using (check_using c = new check_using())
            {
                Console.WriteLine("Executes First");
            }
            Console.WriteLine("Execute Third");
            Console.ReadLine();
        }
    }
}

Output :
Executes First
Execute Second
Execute Third

What is the difference between Interface and Abstract Class in C#?

Abstract ClassInterface
An abstract class can have all access modifiers for member declaration of functions, subs, and properties.An interface is not allowed to have access modifiers for member declaration of functions, subs, properties, etc. All the members are assumed as implicitly public.
A class can at the most use only one abstract class.A class may inherit any number of interfaces.
Multiple inheritance is not supported in abstract class.An interface may support multiple inheritance.
Technically, it’s a class which may or may not contain both definition and its implementation.An interface can only have the signature of functionality so it’s basically an empty shell.
An abstract class can contain members. consts, defined methods, and method stubs.An interface can only contain methods and consts.
It defines the core identity of a class and is used to describe objects of the same data type.It is used to describe the peripheral abilities of a class.
Members of an abstract class cannot be static unless it’s a Complete Member.Members of an interface cannot be static.
It’s ideal for implementations of the same kind and common behavior.It’s better to use interfaces if several implementations share only method signatures.
It can have constructor declaration.It cannot have constructor declaration.
An abstract class has pre-defined fields and constrants.Fields cannot be defined in interfaces.
It can have both abstract and non-abstract methods.It can only have abstract methods.

Can we use “this” command within a static method?

No because static method does not need any object to be called, and this keyword always point to a current object of a class. simply if there is no object then how the keyword point to any current object so,we cannot use this keyword here.

What is the difference between constants and read-only?

Const refers to a constant variable and the value of which need to be assigned only once, during declaration. When the keyword const is used during a declaration, it becomes a constant meaning the value remains constant and cannot be changed throughout the program. It’s more of a reserved word which specifies that a value must not be modified after compile-time. A const is implicitly static by default, so it can be called with the class name using “Classname.VariableName”. The constant values are also called as literals. It can be of any basic data type such as an integer const, a floating const, or a string literal.

The Readonly keyword is a modifier that can be used only on fields but not local variables. A readonly field can be initialized either at the time of declaration or inside a constructor in the same class, so the values can be different for different executions of the program depending on the constructor used. The readonly keyword specifies that an instance variable of an object is not modifiable and any attempt to modify it after declaration results in compilation error. The variable doesn’t become non-modifiable until after the execution. Variables are made readonly only to stop calling the code from accidentally modifying it after it’s constructed.

What are sealed classes in C#?

A sealed class cannot be inherited. Means, no class can be derived from a sealed class. To make a class sealed, we use the keyword sealed in class declaration. For example, if we seal class A as below source code then class B cannot be derived from it. One question arises immediately that can we create object of sealed class in C# program? Answer is, of course we can create object of sealed class. Purpose of sealed class is only to prevent a class to be inherited.

Can we create instance of the class within the same class if we make constructor to private?

It means, if we have a private constructor in a class then its objects can be instantiated within the class only. So in simpler words you can say, if the constructor is private then you will not be able to create its objects outside the class.

What is Idisposable interface?

The .NET classes implement the IDisposable interface, which provides a Dispose method to release unmanaged resources owned by the object instance. This is the standard pattern for releasing non-memory resources in .NET.

.NET Framework defines a interface for types requiring a tear-down method:

public interface IDisposable
{
  void Dispose();
}

Dispose() is primarily used for cleaning up resources, like unmanaged references. However, it can also be useful to force the disposing of other resources even though they are managed. Instead of waiting for the GC to eventually also clean up your database connection, you can make sure it’s done in your own Dispose() implementation.

public void Dispose()
{
   if (null != this.CurrentDatabaseConnection)
   {
       this.CurrentDatabaseConnection.Dispose();
       this.CurrentDatabaseConnection = null;
   }
}

Will garbage collector call dispose method?

The .Net Garbage Collector calls the Object.Finalize method of an object on garbage collection. By default this does nothing and must be overidden if you want to free additional resources.

Dispose is NOT automatically called and must be explicity called if resources are to be released, such as within a ‘using’ or ‘try finally’ block

What is enum in C#?

An enumeration is used in any programming language to define a constant set of values. For example, the days of the week can be defined as an enumeration and used anywhere in the program. In C#, the enumeration is defined with the help of the keyword ‘enum’.

  • The enum is a set of named constant.
  • The value of enum constants starts from 0. Enum can have value of any valid numeric type.
  • String enum is not supported in C#.
  • Use of enum makes code more readable and manageable.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DemoApplication
{
 class Program 
 {
  enum Days{Sun,Mon,tue,Wed,thu,Fri,Sat};
  
  static void Main(string[] args) 
  {
   Console.Write(Days.Sun);
   
   Console.ReadKey();
  }
 }
}

What is the difference between “continue” and “break” statements in C#?

Break (breaks the loop/switch)
Break statement is used to terminate the current loop iteration or terminate the switch statement in which it appears
Continue (skip the execution of current iteration)
The continue statement is not same as break statement. Break statement breaks the loop/switch whereas continue skip the execution of current iteration only and it does not break the loop/switch i.e. it passes the control to the next iteration of the enclosing while loop, do while loop, for loop or for each statement in which it appears.

What is the difference between Array and Arraylist?

ArraysArrayLists
These are strong type collection and allow to store fixed lengthArray Lists are not strong type collection and size will increase or decrease dynamically
In arrays we can store only one datatype either int, string, char etc…
In arraylist we can store all the datatype values
Arrays belong to System.Array namespaceArraylist belongs to System.Collection namespaces

Who will call garbage collector?

Garbage collector is automatically called but sometimes it varies depending on the conditions.

What are Properties in C#?

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.

  • Properties can validate data before allowing a change.
  • Properties can transparently expose data on a class where that data is actually retrieved from some other source such as a database.
  • Properties can take an action when data is changed, such as raising an event or changing the value of other fields.

Does garbage collector called directly by dispose method ?

 The GC will NOT call the Dispose() method on the interface, but it will call the finalizer for your object.

What are extension methods in C#?

Extension Method allows us to add a new method to an existing class:

  • Without modifying it or adding code
  • Without extending it or creating a new derived type
  • Without recompiling the class

Extension methods are a special kind of static method but can be called on objects like an instance method. So, an extension method can be used in the same way as normal instance methods.

Click on this link for the detailed information about extension methods Extension Method

What is the difference between the dispose and finalize methods in C#?

Finalize:

  1. Finalize() belongs to the Object class.
  2. It is automatically called by the Garbage Collection mechanism when the object goes out of the scope(usually at the end of the program
  3. It is slower method and not suitable for instant disposing of the objects.
  4. It is non-deterministic function i.e., it is uncertain when Garbage Collector will call Finalize() method to reclaim memory.
class employee
{
//This is the destructor of emp class
~employee()
{

}
//This destructor is implicitly compiled to the Finalize method.
}

Dispose:

  1. Dispose() belongs to the IDisposable interface
  2. We have to manually write the code to implement it(User Code)
    ex: if we have emp class we have to inherit it from the IDisposable interface
    and write code. We may have to suppress the Finalize method using GC.SuppressFinalize() method.
  3. Faster method for instant disposal of the objects.
  4. It is deterministic function as Dispose() method is explicitly called by the User Code.
user interface Controls. Forms, SqlConnection class have built in implementaion of Dispose method.

try
{

string constring = "Server=(local);Database=my; User Id=sa; Password=sa";
SqlConnection sqlcon = new SqlConnection(constring);
sqlcon.Open(); // here connection is open


// some code here which will be execute
}
catch
{
// code will be execute when error occurred in try block
}
finally
{
sqlcon.Close(); // close the connection
sqlcon.Dispose(); // detsroy the connection object
}

You can also check this link Difference between Finalize, Destructor and Dispose in C#

What are the differences between System.String and System.Text.StringBuilder classes?

A string instance is immutable. Immutable means once we create a string object we cannot modify the value of the string Object in the memory. Any operation that appears to modify the string, it will discard the old value and it will create new instance in memory to hold the new value.

The System.Text.StringBuilder is mutable, that means once we create StringBuilder object we can perform any operation that appears to change the value without creating new instance for every time. It can be modified in any way and it doesn’t require creation of new instance.

You can also check this link string and StringBuilder

What is Thread safe collection is c#?

The .NET Framework 4 introduces the System.Collections.Concurrent namespace, which includes several collection classes that are both thread-safe and scalable. Multiple threads can safely and efficiently add or remove items from these collections, without requiring additional synchronization in user code. When you write new code, use the concurrent collection classes whenever multiple threads will write to the collection concurrently.

Sr.NoType & Description
1BlockingCollection<T> Bounding and blocking functionality for any type.
2ConcurrentDictionary<TKey,TValue> Thread-safe implementation of a dictionary of key-value pairs.
3ConcurrentQueue<T> Thread-safe implementation of a FIFO (first-in, first-out) queue.
4ConcurrentStack<T> Thread-safe implementation of a LIFO (last-in, first-out) stack.
5ConcurrentBag<T> Thread-safe implementation of an unordered collection of elements.
6IProducerConsumerCollection<T> The interface that a type must implement to be used in a BlockingCollection

What is Thread synchronisation?

Thread Synchronization is a mechanism which ensures that two or more concurrent process or threads do not execute some particular section of program especially critical section. In this technique one thread executes the critical section of a program and other thread wait until the first thread finishes execution. If proper synchronization mechanism will be not applied then race condition will happen. Thread Synchronization Deals with the following conditions:

  1. Deadlock
  2. Starvation
  3. Priority Inversion
  4. Busy Waiting

TheFollowing are some classic problems of Synchronization:

  1. The Producer-Consumer Problem
  2. The Readers-Writers Problem
  3. The Dining Philosopher Problem

These problems are used to test every newly proposed synchronization techniques.

What are delegates in C# and the uses of delegates?

A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the developer to encapsulate a reference to a method inside a delegate object.

Delegates are basically used in these situations:

  • These are used to represent or refer to one or more functions.
  • These can only be used to define call-back methods.
  • In order to consume a delegate, we need to create an object to delegate.

Syntax of delegates is :

[modifier] delegate [returntype] [delegatename] ([parameterlist]);

modifier: It is the required modifier which defines the access of delegate and it is optional to use.

delegateIt is the keyword which is used to define the delegate.

returntypeIt is the type of value returned by the methods which the delegate will be going to call. It can be void. A method must have the same return type as the delegate.

delegatename: It is the user-defined name or identifier for the delegate.

parameterlist: This contains the parameters which are required by the method when called through the delegate.

Please follow this link for more detail about delegates. What are Delegates and what are the uses of the Delegates

Can a private virtual method can be overridden?

You can’t even declare private virtual methods. The only time it would make any sense at all would be if you had:

public class Outer
{
    private virtual void Foo() {}

    public class Nested : Outer
    {
        private override void Foo() {}
    }
}

… that’s the only scenario in which a type has access to its parent’s private members. However, this is still prohibited:

Test.cs(7,31): error CS0621: ‘Outer.Nested.Foo()’: virtual or abstract members cannot be private
Test.cs(3,26): error CS0621: ‘Outer.Foo()’: virtual or abstract members cannot be private

What are partial classes?

When working on large projects, spreading a class over separate physical files enables multiple developers to work on it at the same time. Partial classes allow for a single Class file to be split up across multiple physical files, and all parts are combined when the application is compiled.

Entire Class definition in one file (billing.cs).

public class Billing
{
    public bool Add()
    {
    }
    public bool Edit()
    {
    }
}

Same class in the above code split across multiple files.
billing_1.cs
 
public partial class Billing
{
    public bool Add()
    {
    }
}

billing_2.cs
 
public partial class Billing
{
    public bool Edit()
    {
    }
}

What are generics in C#.NET?

In c#, generic is a type which is used to define a class,structure,interface or method with a placeholders (type parameters) to indicate that they can store or use one or more of the types. C#, the compiler will replace a placeholders with the specified type at compile time.

C#, mostly we will use a generics with collections and the methods that operate on them to specify a type of objects to be stored in a collections. The generics are introduced in .NET Framework 2.0 with a new namespace called System.Collections.Generic

In c#, generics are useful to improve the code re-usability, type safety and the performance when compared with the non-generic types such as arraylist.

Please follow this link for more detail about Generics. Generic in C#

What is IEnumerable<> in C#?

IEnumerable

IEnumerable is an interface that defines one method GetEnumerator which returns an IEnumerator interface; this, in turn, allows read-only access to a collection.

The collection that implements IEnumerable can be used with a foreach statement.

IEnumerable enables you to iterate through the collection using a for-each loop.

So if your intention is just that, IEnumerable can help you achieve it with minimum effort (implementation of only one method – GetEnumerator()).

List, on the other hand, is a pre-implemented type-safe collection (using generic type) class available in the framework. This already has the implementation of IList, ICollection & IEnumerable.

So functionally IEnumerable is a subset of List. Also, List is a class whereas IEnumerable would need implementation.

Give me an example where internal preferred over public?

First of all, let’s establish that there is no technical difference between the two. public in C# means “accessible to anyone who can see the class”; making a public member of an internal class does not make the member more accessible than making it internal would.

There are good arguments for both sides.

The pro-internal argument is that the method is effectively internal, and you want to be able to glance at a method declaration and know whether it can be called by external code, whether it needs to be documented, whether it needs to verify that its arguments are valid, and so on.

internal interface I 
{
  void M();
}
internal sealed class C : I
{
  public void M() { ... }
}

Even though I and C are both internal, the language requires that M be public in order to implement I.M.
As you could probably tell, I am strongly in favour of the “public” option. However there are some members of the C# compiler team that are in the “internal” camp; it’s not an unreasonable position. My advice is to discuss the issue amongst your team, make a decision, and then stick to it. That way you’ll all be able to read and understand the intention of the code.

What kind of access specifier in C#?

Access modifiers are an integral part of object-oriented programming. It are used to implement encapsulation of OOP. Access modifiers allow you to define who does or who doesn’t have access to certain features.

  • public: The 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 be accessed only by code in the same class or struct.
  • protected: The type or member can be accessed only by code in the same class, or in a class that is derived from that 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 assembly in which it’s declared, or from within a derived class in another assembly.
  • private protected: The type or member can be accessed only within its declaring assembly, by code in the same class or in a type that is derived from that class.

Please follow this link for more detail about Access Modifiers in C#.

What is the difference between late binding and early binding in C#?

Early Binding

The name itself describes that compiler knows about what kind of object it is, what are all the methods and properties it contains. As soon as you declared the object, .NET Intellisense will populate its methods and properties on click of the dot button.

Common Examples:

ComboBox cboItems;

ListBox lstItems;
In the above examples, if we type the cboItem and place a dot followed by, it will automatically populate all the methods, events and properties of a combo box, because compiler already know it’s an combobox.

Late Binding

The name itself describes that compiler does not know what kind of object it is, what are all the methods and properties it contains. You have to declare it as an object, later you need get the type of the object, methods that are stored in it. Everything will be known at the run time.

Common Examples:

Object objItems;

objItems = CreateObject(“DLL or Assembly name”);
Here during the compile time, type of objItems is not determined. We are creating an object of a dll and assigning it to the objItems, so everything is determined at the run time.

Early Binding vs. Late Binding

Now coming into the picture…

  • Application will run faster in Early binding, since no boxing or unboxing are done here.
  • Easier to write the code in Early binding, since the intellisense will be automatically populated
  • Minimal Errors in Early binding, since the syntax is checked during the compile time itself.
  • Late binding would support in all kind of versions, since everything is decided at the run time.
  • Minimal Impact of code in future enhancements, if Late Binding is used.
  • Performance will be code in early binding.

What is IEnumerable, IEnumerator, ICollection and IList,IQueryable in C#

Please refer to this article. https://blog.codehunger.in/what-is-ienumerable-ienumerator-icollection-and-ilist-in-c/

Difference between Convert.ToString and .ToString() method

The basic difference between them is “Convert.ToString(variable)” handles NULL values even if variable value become null but “variable.ToString()” will not handle NULL values it will throw a NULL reference exception error. So as a good coding practice using “convert” is always safe.

/Returns a null reference exception for Name.
string Name;
object i = null;
Name= i.ToString();

//Returns an empty string for name and does not throw an exception.
string Name;
object i = null;
Name = Convert.ToString(i);

What are Filters and Attributes in ASP.NET MVC?

Please refer to this article https://blog.codehunger.in/asp-net-mvc-filters-and-attributes/

LINQ Single vs SingleOrDefault vs First vs FirstOrDefault

SINGLE()SINGLEORDEFAULT()FIRST()FIRSTORDEFAULT()
DESCRIPTIONReturns a single, specific element of a sequenceReturns a single, specific element of a sequence, or a default value if that element is not foundReturns the first element of a sequenceReturns the first element of a sequence, or a default value if no element is found
EXCEPTION THROWNThere are 0 or more than 1 elements in the resultThere is more than one element in the resultThere are no elements in the resultOnly if the source is null (they all do this)
WHEN TO USEIf exactly 1 element is expected; not 0 or more than 1When 0 or 1 elements are expectedWhen more than 1 element is expected and you want only the firstWhen more than 1 element is expected and you want only the first. Also it is ok for the result to be empty

ViewData vs ViewBag vs TempData vs Session

Please refer to this article https://blog.codehunger.in/viewdata-vs-viewbag-vs-tempdata-vs-session/

What is Difference between Html.Partial and Html.RenderPartial in MVC?

Please refer to this article https://blog.codehunger.in/what-is-difference-between-html-partial-and-html-renderpartial-in-mvc/

DataSet Vs DataReader

Please refer to this article https://blog.codehunger.in/dataset-vs-datareader/

Tempdata.Keep() and Tempdata.Peek()

Keep() MethodPeek() Method
1.To read and retain the value with Keep one need to do two request, i.e. first read the value and in next statement call Keep method to retain value.With the help of Peek method one can do both operation in a single statement i.e. access as well retain value.
2.Keep provides 2 overload methods. One can save particular TempData on condition based and second can save all TempData’s value.There is no overloaded method in case of Peek method. Peek method always saves particular TempaData’s value.
3.RedirectResult and RedirectToRouteResult internally calls Keep method to retain items.Peek method is not called internally with any of ActionResult.
4.Once we retrieved value from object than it is marked for deletion, with Keep method we can later save object from Deletion. It means first deletion marking is happened then saving using Keep method.With Peek method we can retain TempData value without marking for deletion in a single call. It means deletion marking is not happening in case of Peek method. It directly persist TempData.

How to use left join in Entity Framework

A Left outer join is a join in which each element of the first collection is returned, regardless of whether it has any correlated elements in the second collection. It can be performed by calling the DefaultIfEmpty() method on the results of a group join.

var result= (from st in db.StudentMaster
                  join cos in db.CourseMaster on st.CourseId equals cos.CourseId into     studentdet
                  from stu in  studentdet.DefaultIfEmpty()
                  select new { st.StudentName,cos.CourseName} )

Why multiple inheritance not allowed in C#?

The one of problem for not supporting the multiple inheritance lies in the Diamond Problem.

The diamond problem is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If a method in D calls a method defined in A (and does not override the method), and B and C have overridden that method differently, then from which class does it inherit: B, or C?

Please refer to this article for more details Why multiple inheritance not allowed in C#?

Weak References in .Net

Weak references in .Net create references to large objects in your application that are used infrequently so that they can be reclaimed by the garbage collector if needed. Let me explain you what basically Weak Reference is.

weak reference is a way to have some pointer to an object that does have any reference (strong reference). In .NET, any normal reference to another object is a strong reference . That is, when you declare a variable of a type that is not a primitive/value type, you are declaring a strong reference.

Please refer to this article for more details https://blog.codehunger.in/weak-references-in-net/

Difference between Model and ViewModel in MVC

Please refer to this article : https://blog.codehunger.in/difference-between-model-and-viewmodel-in-mvc/

Abstraction and Encapsulation in C#

Encapsulation is all about wrapping data and Abstraction is about hiding the implementation details.

Encapsulation 

It is the concept of OOP in which we hide the internal details or state of a class from the outside word. The fields or variables of the class define the state of a class. If we make these  fields public then anyone outside the class can access it and should be able to change the state of class.

  • Wrapping up a data member and a method together into a single unit (in other words class) is called Encapsulation.
  • Encapsulation is like enclosing in a capsule. That is enclosing the related operations and data related to an object into that object.
  • Encapsulation means hiding the internal details of an object, in other words how an object works.
  • Encapsulation prevents clients from seeing its inside view, where the behavior of the abstraction is implemented.
  • It is a technique used to protect the information in an object from another object.
  • Hide the data for security such as making the variables private, and expose the property to access the private data that will be public.
  • Encapsulation is like you can play music in either of mobile. It means this is the property of encapsulating members and functions.
Abstraction 

In object Oriented programming if objects are the heart of modelling, then why bother with classes? The notion of abstraction is at the heart of matter. By grouping objects into classes we abstract a problem. Abstraction gives modelling its power and ability to generalize from a few specific cases to a host of similar cases.

  • It is “To represent the essential feature without representing the background details.”
  • Lets you focus on what the object does instead of how it does it.
  • It provides you a generalized view of your classes or objects by providing relevant information.
  • It is the process of hiding the working style of an object, and showing the information of an object in an understandable manner.

Please refer to this article for more details https://blog.codehunger.in/abstraction-and-encapsulation-in-c/

Difference between Hashtable and Dictionary in C#

Please refer to this article for more details https://blog.codehunger.in/difference-between-hashtable-and-dictionary-in-c/

Shaiv Roy

Hy Myself shaiv roy, I am a passionate blogger and love to share ideas among people, I am having good experience with laravel, vue js, react, flutter and doing website and app development work from last 7 years.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Check Also
Close
Back to top button