We are providing all c sharp questions and answers so it will make your interiview easy.
You would always know C is the procedural language while C# is a more object-oriented language. The biggest difference is that C# supports automatic garbage collection by Common Language Runtime (CLR) while C does not. C# primarily needs a .NET framework to execute while C is a platform-agnostic language.
CLR handles program execution for various languages including C#. The architecture of CLR handles memory management, garbage collection, and security handling, and looks like this:
Garbage collection is the process of freeing up memory that is captured by unwanted objects. When you create a class object, automatically some memory space is allocated to the object in the heap memory. Now, after you perform all the actions on the object, the memory space occupied by the object becomes waste. It is necessary to free up memory. Garbage collection happens in three cases:
Class is an entity that encapsulates all the properties of its objects and instances as a single unit. C# has four types of such classes:
1-Static class: Static class, defined by the keyword ‘static’ does not allow inheritance. Therefore, you cannot create an object for a static class.
2-Partial class: Partial class, defined by the keyword ‘partial’ allows its members to partially divide or share source (.cs) files.
3-Abstract class: Abstract classes are classes that cannot be instantiated where you cannot create objects. Abstract classes work on the OOPS concept of abstraction. Abstraction helps to extract essential details and hide the unessential ones.
4-Sealed class: Sealed classes are classes that cannot be inherited. Use the keyword sealed to restrict access to users to inherit that class.
sealed class InterviewBit
{
// data members
// methods
}
Managed code lets you run the code on a managed CLR runtime environment in the .NET framework.
Managed code runs on the managed runtime environment rather than the operating system itself.
Benefits: Provides various services like a garbage collector, and exception handling.
Unmanaged code is when the code doesn’t run on CLR, it is an unmanaged code that works outside the .NET framework.
They don’t provide services in high-level languages and therefore, run without them. Such an example is C++.
Let’s dig into the differences between an abstract class and an interface:
Abstract classes are classes that cannot be instantiated ie. that cannot create an object. The interface is like an abstract class because all the methods inside the interface are abstract
Surprisingly, abstract classes can have both abstract and non-abstract methods but all the methods of an interface are abstract
Since abstract classes can have both abstract and non-abstract methods, we need to use the Abstract keyword to declare abstract methods. But in the interface, there is no such need.
An abstract class has constructors while an interface encompasses none.
1-Abstract class:
public abstract class Shape{
public abstract void draw();
}
2-Interface:
public interface Paintable{
void paint();
}
C# ref keywords pass arguments by reference and not value. To use the ‘ref’ keyword, you need to explicitly mention ‘ref’.
void Method(ref int refArgument)
{
refArgument = refArgument + 10;
}
int number = 1;
Method(ref number);
Console.WriteLine(number);
C# out keywords pass arguments within methods and functions.
‘The out’ keyword is used to pass arguments in a method as a reference to return multiple values. Although it is the same as the ref keyword, the ref keyword needs to be initialized before it is passed. Here, The out and ref keywords are useful when we want to return a value in the same variables that are passed as an argument.
public static string GetNextFeature(ref int id)
{
string returnText = "Next-" + id.ToString();
id += 1;
return ret return text
}
public static string GetNextFeature(out int id)
{
id = 1;
string returnText = "Next-" + id.ToString();
return return text;
}
Extension methods help to add new methods to the existing ones. The methods that are added are static. At times, when you want to add methods to an existing class but don’t perceive the right to modify that class or don’t hold the rights, you can create a new static class containing the new methods. Once the extended methods are declared, bind this class with the existing one and see if the methods will be added to the existing one.
In C# collections, defining any kind of object is termed okay which compromises C#’s basic rule of type-safety. Therefore, generics were included to type-safe the code by allowing re-use of the data processing algorithms. Generics in C# mean not linked to any specific data type. Generics reduce the load of using boxing, unboxing, and typecasting objects. Generics are always defined inside angular brackets <>. To create a generic class, this syntax is used:
GenericList<float> list1 = new GenericList<float>();
GenericList<Features> list2 = new GenericList<Features>();
GenericList<Struct> list3 = new GenericList<Struct>();
Here, GenericList<float> is a generic class. In each of these instances of GenericList<T>, every occurrence of T in the class is substituted at run time with the type argument. By substituting the T, we have created three different type-safe using the same class.
An array is a collection of similar variables clubbed together under one common name. While ArrayList is a collection of objects that can be indexed individually. With ArrayList you can access several features like dynamic memory allocation, adding, searching, and sorting items in the ArrayList.
1-When declaring an array the size of the items is fixed therefore, the memory allocation is fixed. But with ArrayList, it can be increased or decreased dynamically.
2-Array belongs to the system. an array namespace while ArrayList belongs to the system. c collection namespace.
3-All items in an array are of the same datatype while all the items in an ArrayList can be of the same or different data types.
4-While arrays cannot accept null, ArrayList can accept null values.
/ /C# program to illustrate the ArrayList using System; using System.Collections;
class IB {
// Main Method public static void Main(string[] args) {
// Create a list of strings ArrayList al = new ArrayList(); al.Add("Bruno"); al.Add("Husky"); al.Add(10); al.Add(10.10);
// Iterate list element using for for-each for each name in al) { Console.WriteLine(names); } } }
|
Inheritance means acquiring some of the properties from a master class.
Here, class C can inherit properties from Class A and Class B. Here is an example of inheritance:
// C# program to illustrate // multiple class inheritance using System; using System.Collections; // Parent class 1 class Scaler { // Providing the implementation // of features() method public void features() { // Creating ArrayList ArrayList My_features= new ArrayList(); // Adding elements in the // My_features ArrayList My_features.Add("Abstraction"); My_features.Add("Encapsulation"); My_features.Add("Inheritance"); Console.WriteLine("Features provided by OOPS:"); foreach(var elements in My_features) { Console.WriteLine(elements); } } } // Parent class 2 class Scaler2 :Scaler{ // Providing the implementation // of courses() method public void languages() { // Creating ArrayList ArrayList My_features = new ArrayList(); // Adding elements in the // My_features ArrayList My_features.Add("C++"); My_features.Add("C#"); My_features.Add("JScript"); Console.WriteLine("\nLanguages that use OOPS concepts:"); foreach(var elements in My_features) { Console.WriteLine(elements); } } } // Child class class ScalertoScaler : Scaler2 { } public class Scaler1 { // Main method static public void Main() { // Creating object of ScalertoScaler class ScalertoScaler obj = new ScalertoScaler(); obj.features(); obj.languages(); } } |
Also, C# doesn’t support multiple inheritances.
Instead, you can use interfaces to inherit the properties using the class name in the signature.
The two functions are used for typecasting the data types:
Boxing: Boxing converts value type (int, char, and others.) to reference type (object) which is an implicit conversion process using object value.
int num = 23; // 23 will assigned to num Object Obj = num; // Boxing |
Unboxing: Unboxing converts reference type (object) to value type (int, char, and others.) using an explicit conversion process
Example:
int num = 23; // value type is int and assigned value 23 Object Obj = num; // Boxing int i = (int)Obj; // Unboxing |
Properties in C# are public members of a class where they provide the ability to access private members of a class. The basic principle of encapsulation lets you hide some sensitive properties from the users by making the variables private. The private members are not accessible otherwise in a class. Therefore, by using properties in C# you can easily access the private members and set their values.
The values can be easily assigned using get and set methods, also known as accessors. While the get method extracts the value, the set method assigns the value to the variables.
public partial Clas_name { // code } |
You can easily split the functionalities of methods, interfaces, or structures into multiple files. You can even add nested partial classes.
Late binding and early binding are examples of one of the primary concepts of OOPS: Polymorphism.
For ex: one function calculateBill() will calculate the ills of premium customers, basic customers, and semi-premium customers based on their policies differently. The calculation for all the customer objects is done differently using the same function which is called polymorphism.
When an object is assigned to an object variable in C#, the .NET framework performs the binding.
When the binding function happens at compile-time, it is called early binding. It investigates and checks the methods and properties of static objects. With early binding, the number of run-time errors decreases substantially and it executes pretty quickly.
But when the binding happens at runtime, it is called late binding. Late binding happens when the objects are dynamic (decided based on the data they hold
at run-time. It is slower as it looks through during run-time
When a group of similar elements is clubbed together under one name, they are called arrays.
For ex. An array of tea Atea[4]: [green tea, chamomile tea, black tea, lemon tea]. The length of the array defines how many elements are present in the array.
In C#, the memory allocations for the elements of the array happen dynamically. This is how values are stored in an array sequentially.
A few pointers for arrays in C#:
1-The memory allocation is DYNAMIC.
2-Arrays in C# are treated as objects.
3-The length of the array is easy to find by detecting the number of members in the array.
4-The members in the array are ordered and begin with the index value=0.
5-The array types are reference types derived from the base array type.
Syntax: < Data Type > [ ] < Name_Array >
Indexers are called smart arrays that allow access to a member variable. Indexers allow member variables to use the features of an array. They are created using the Indexer keyword. Indexers are not static members.
For ex. Here the indexer is defined in the same way.
<return type> this[<parameter type> index] { get{ // return the value from the specified index of an internal collection } set{ // set values at the specified index in an internal collection } } |
Although both are used to compare two objects by value, still they are used differently.
int x = 10; int y = 10; Console.WriteLine( x == y); Console.WriteLine(x.Equals(y)); Output: True True |
The equality operator (==) is a reference type which means that if the equality operator is used, it will return true only if both the references point to the same object.
Equals() method: EThe quals method is used to compare the values carried by the objects. int x=10, int y=10. If x==y is compared then, the values carried by x and y are compared which is equal and therefore they return true.
Equality operator: Compares by reference
Equals(): Compares by value
Overloading means when a method has the same name but carries different values to use in a different context. Only the main() method cannot be overloaded
In Toerload methods in C#,
Change the number of parameters in a method, or
Use different data types for parameters
In these ways, you can overload a method multiple times.
public class Area { public double area(double x) { double area = x * x; return area; } public double area(double a, double b) { double area = a * b; return area; } } |
Here, the method Area is used twice. In the first declaration, one argument is used while in the second one, there were two arguments are used. Using different parameters in the same method, we were able to overload the method area()
Reflection in C# extracts metadata from the datatypes during runtime.
1-Assembly
2-Module
3-Enum
4-MethodInfo
5-ConstructorInfo
6-MemberInfo
7-ParameterInfo
8-Type
9-FieldInfo
10-EventInfo
11-PropertyInfo
A const keyword in C# is used to declare a constant field throughout the program. That means once a variable has been declared const, its value cannot be changed throughout the program.
In C#, a constant is a number, string, null reference, or boolean value.
class IB { // Constant fields public const int xvar = 20; public const string str = "InterviewBit"; // Main method static public void Main() { // Display the value of Constant fields Console.WriteLine("The value of xvar: {0}", xvar); Console.WriteLine("The value of str: {0}", str); } } Output: The value of xvar is 20. The value of strike ng is Interview Bit |
On the other hand, with a read-only keyword, you can assign the variable only when it is declared or in a constructor of the same class in which it is declared.
public readonly int xvar1; public readonly int yvar2; // Values of the readonly // variables are assigned // Using constructor public IB(int b, int c) { xvar1 = b; yvar2 = c; Console.WriteLine("The value of xvar1 {0}, "+ "and yvar2 {1}", xvar1, yvar2); } // Main method static public void Main() { IB obj1 = new IB(50, 60); } } Output: The value of xvar1 is 50, and yvar2 is 60 |
Constants are static by default while read-only should have a value assigned when the constructor is declared.
Constants can be declared within functions while read-only modifiers can be used with reference types.
The major difference between String and StringBuilder is that String objects are immutable while StringBuilder creates a mutable string of characters. StringBuilder will make the changes to the existing object rather than creating a new object.
StringBuilder simplifies the entire process of making changes to the existing string object. Since the String class is immutable, it is costlier to create a new object every time we need to make a change. So, the StringBuilder class comes into the picture which can be evoked using the System.Tex t namespace.
In case, a string object will not change throughout the entire program, then use String class or else StringBuilder.
string s = string.Empty; for (i = 0; i < 1000; i++) { s += i.ToString() + " "; } |
Here, you’ll need to create 2001 objects out of which 2000 will be of no use.
The same can be applied using StringBuilder:
StringBuilder sb = new StringBuilder(); for (i = 0; i < 1000; i++) { sb.Append(i); sb.Append(' '); } |
By using StringBuilder here, you also de-stress the memory allocator.