Part 2

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

Using break statement, you can 'jump out of a loop' whereas by using a continue statement, you can 'jump over one iteration' and then resume your loop execution.

public static void main(String[] args)
{
    for (int i = 0; i < 5; i++)
    {
        if (i == 5)
            break;

        Console.WriteLine("The number is " + i);
        Console.ReadLine();
    }
}

// The number is 0
// The number is 1
// The number is 2
// The number is 3
 public static void main(String[] args)
{
    for (int i = 0; i < 5; i++)
    {
        if (i == 4)
            continue;

        Console.WriteLine("The number is " + i);
        Console.ReadLine();
    }
}

// The number is 0
// The number is 1
// The number is 3
// The number is 5

What is the difference between constant and readonly in C#?

Const is nothing but "constant", a variable of which the value is constant but at compile time. It's mandatory to assign a value to it. By default, a const is static and we cannot change the value of a const variable throughout the entire program.

Readonly is the keyword whose value we can change during runtime or we can assign it at run time but only through the non-static constructor.

class Test
{
    readonly int read = 10;
    const int cons = 10;
    public Test()
    {
        read = 100;
        cons = 100;
    }

    public void DoSomething()
    {
        Console.WriteLine("Read only : {0}, " + read);
        Console.WriteLine("Read only : {0}, " + cons);
    }
}

Here, I was trying to change the value of both the variables in the constructor, but when I try to change the constant, it gives an error to change its value in the block that I have to call at run time.

Finally, remove that line of code from class and call this Check() function like in the following code snippet:

class Program
{
    static void Main(String[] args)
    {
        Test testObj = new Test();
        testObj.Check();
    }
}

class Test
{
    readonly int read = 10;
    const int cons = 10;
    public Test()
    {
        read = 100;
    }

    public void Check()
    {
        Console.WriteLine("Read only : {0}, " + read);
        Console.WriteLine("Read only : {0}, " + cons);
    }
}

What is the difference between ref and out keywords?

The ref keyword passes arguments by reference. It means any changes made to this argument in the method will be reflected in that variable when control returns to the calling method. The out keyword passes arguments by reference. This is very similar to the ref keyword.

Can “this” be used within a static method?

We can't use 'this' in a static method because the keyword 'this' returns a reference to the current instance of the class containing it. Static methods (or any static member) do not belong to a particular instance. They exist without creating an instance of the class and are called with the name of a class, not by instance, so we can’t use this keyword in the body of static Methods. However, in the case of Extension Methods, we can use the parameters of the function.

Let’s have a look at the “this” keyword.

What are Properties in C#?

C# properties are members of a C# class that provides a flexible mechanism to read, write or compute the values of private fields, in other words, by using properties, we can access private fields and set their values. Properties in C# are always public data members. C# properties use get and set methods, also known as accessors, to access and assign values to private fields.

What are accessors?

The get and set portions or blocks of a property are called accessors. These are useful to restrict the accessibility of a property. The set accessor specifies that we can assign a value to a private field in a property. Without the set accessor property, it is like a readonly field. With the 'get' accessor we can access the value of the private field. In other words, it returns a single value. A Get accessor specifies that we can access the value of a field publically.

public int Number { get; set; }
public string String { get; set; }

What is the difference between String and StringBuilder in C#?

String

A string is an immutable object. Immutable is when we create string objects in code so we cannot modify or change that object in any operations like insert new value, replace or append any value with the existing value in a string object. When we have to do some operations to change string simply it will dispose of the old value of string object and it will create a new instance in memory for hold the new value in a string object, for example:

class Program
{
    static void Main(string[] args)
    {
        string val = "Hello";
        val += "am";
        val += "Hugh Jackman";
        Console.WriteLine(val);
    }
}
  • It’s an immutable object that holds a string value.

  • Performance-wise, string is slow because it creates a new instance to override or change the previous value.

  • String belongs to the System namespace.

StringBuilder

System.Text.Stringbuilder is a mutable object which also holds the string value, mutable means once we create a System.Text.Stringbuilder object. We can use this object for any operation like insert value in an existing string with insert functions also replace or append without creating a new instance of System.Text.Stringbuilder for every time so it’s using the previous object. That way, it works fast compared to the System.String. Let’s see an example to understand System.Text.Stringbuilder.

class Program
{
    static void Main(string[] args)
    {
        StringBuilder val = new StringBuilder("");
        val.Append("Hello");
        val.Append(" am Hugh Jackman");
        Console.WriteLine(val);
    }
}
  • StringBuilder is a mutable object.

  • Performance-wise StringBuilder is very fast because it will use the same instance of StringBuilder object to perform any operation like inserting a value in the existing string.

  • StringBuilder belongs to System.Text.Stringbuilder namespace.

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

A Delegate is an abstraction of one or more function pointers (as existed in C++; the explanation about this is out of the scope of this article). The .NET has implemented the concept of function pointers in the form of delegates. With delegates, you can treat a function as data. Delegates allow functions to be passed as parameters, returned from a function as a value, and stored in an array. Delegates have the following characteristics:

  • Delegates are derived from the System.MulticastDelegate class.

  • They have a signature and a return type. A function that is added to delegates must be compatible with this signature.

  • Delegates can point to either static or instance methods.

  • Once a delegate object has been created, it may dynamically invoke the methods it points to at runtime.

  • Delegates can call methods synchronously and asynchronously.

The delegate contains a couple of useful fields. The first one holds a reference to an object, and the second holds a method pointer. When you invoke the delegate, the instance method is called on the contained reference. However, if the object reference is null then the runtime understands this to mean that the method is a static method. Moreover, invoking a delegate syntactically is the exact same as calling a regular function. Therefore, delegates are perfect for implementing callbacks.

Why Do We Need Delegates?

Historically, the Windows API made frequent use of C-style function pointers to create callback functions. Using a callback, programmers were able to configure one function to report back to another function in the application. So the objective of using a callback is to handle button-clicking, menu-selection, and mouse-moving activities. But the problem with this traditional approach is that the callback functions were not type-safe. In the .NET framework, callbacks are still possible using delegates with a more efficient approach. Delegates maintain three important pieces of information:

  • The parameters of the method.

  • The address of the method it calls.

  • The return type of the method.

A delegate is a solution for situations in which you want to pass methods around to other methods. You are so accustomed to passing data to methods as parameters that the idea of passing methods as an argument instead of data might sound a little strange. However, there are cases in which you have a method that does something, for instance, invoking some other method. You do not know at compile time what this second method is. That information is available only at runtime, hence Delegates are the device to overcome such complications.

What is IEnumerable<> in C#?

IEnumerable is the parent interface for all non-generic collections in System.Collections namespace like ArrayList, HastTable etc. that can be enumerated. For the generic version of this interface as IEnumerable<T> which is a parent interface of all generic collections class in System.Collections.Generic namespace like List<> and more.

In System.Collections.Generic.IEnumerable<T> have only a single method which is GetEnumerator() that returns an IEnumerator. IEnumerator provides the power to iterate through the collection by exposing a Current property and Move Next and Reset methods if we don’t have this interface as a parent so we can’t use iteration by foreach loop or can’t use that class object in our LINQ query.

What are the differences between IEnumerable and IQueryable?

Before we go into the differences, let's learn what the IEnumerable and IQueryable are.

IEnumerable

Is the parent interface for all non-generic collections in System.Collections namespace like ArrayList, HastTable, etc. that can be enumerated. The generic version of this interface is IEnumerable<T>, which is a parent interface of all generic collections in System.Collections.Generic namespace, like List<> and more.

IQueryable

As per MSDN, the IQueryable interface is intended for implementation by query providers. It is only supposed to be implemented by providers that also implement IQueryable<T>. If the provider does not also implement IQueryable<T>, the standard query operators cannot be used on the provider's data source.

The IQueryable interface inherits the IEnumerable interface so that if it represents a query, the results of that query can be enumerated. Enumeration causes the expression tree associated with an IQueryable object to be executed. The definition of "executing an expression tree" is specific to a query provider. For example, it may involve translating the expression tree to an appropriate query language for the underlying data source. Queries that do not return enumerable results are executed when the Execute method is called.

What are Singleton Design Patterns and how to implement them in C#?

What is a Singleton Design Pattern?

  1. Ensures a class has only one instance and provides a global point of access to it.

  2. A Singleton is a class that only allows a single instance of itself to be created and usually gives simple access to that instance.

  3. Most commonly, singletons don't allow any parameters to be specified when creating the instance since the second request of an instance with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same parameter then the factory pattern is more appropriate.)

  4. There are various ways to implement the Singleton Pattern in C#. The following are the common characteristics of a Singleton Pattern.

    • A single constructor, that is private and parameterless.

    • The class is sealed.

    • A static variable that holds a reference to the single created instance, if any.

    • A public static means of getting the reference to the single created instance, creating one if necessary.

What are Generics in C#?

Generics allow you to delay the specification of the data type of programming elements in a class or a method until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.

You write the specifications for the class or the method, with substitute parameters for data types. When the compiler encounters a constructor for the class or a function call for the method, it generates code to handle the specific data type.

Features of Generics

Generics are a technique that enriches your programs in the following ways:

  • It helps you to maximize code reuse, type safety, and performance.

  • You can create generic collection classes. The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. You may use these generic collection classes instead of the collection classes in the System.Collections namespace.

  • You can create your own generic interfaces, classes, methods, events, and delegates.

  • You may create generic classes constrained to enable access to methods on specific data types.

  • You may get information on the types used in a generic data type at run-time using reflection.

public class Report<T, U>
{
    public int MyProperty1 { get; set; }
    public T MyProperty2 { get; set; }
    public U MyProperty3 { get; set; }
}

public class PrintInfo
{
    public void Print<T, U> (Report<T, U> report)
    {
        Console.WriteLine(report.MyProperty1);
        Console.WriteLine(report.MyProperty2);
        Console.WriteLine(report.MyProperty3);
    }
}

What is a Virtual Method in C#?

A virtual method is a method that can be redefined in derived classes. A virtual method has an implementation in a base class as well as derived from the class. It is used when a method's basic functionality is the same but sometimes more functionality is needed in the derived

class.The virtual keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class. For example, this method can be overridden by any class that inherits it:

public virtual void MyMethod()
{
    return x * y;
}

What is LINQ in C#?

LINQ stands for Language Integrated Query. LINQ is a data querying methodology that provides querying capabilities to .NET languages with a syntax similar to a SQL query.

What is Reflection in C#?

Reflection is the process of runtime type discovery to inspect metadata, CIL code, late binding, and self-generating code. At the run time by using reflection, we can access the same "type" information as displayed by the ildasm utility at design time. The reflection is analogous to reverse engineering in which we can break an existing *.exe or *.dll assembly to explore defined significant contents information, including methods, fields, events, and properties.

You can dynamically discover the set of interfaces supported by a given type using the System.Reflection namespace.

Reflection typically is used to dump out the loaded assemblies list, their reference to inspect methods, properties etcetera. Reflection is also used in the external disassembling tools such as Reflector, Fxcop, and NUnit because .NET tools don't need to parse the source code similar to C++.

public static void FieldsInvestigation(Type T)
{
    FieldInfo[] fld = T.GetFields();
    MethodInfo[] mtd = T.GetMethods();

    // Get fields
    foreach (var item in fld)
        Console.WriteLine("-->{0}", item.Name);

    // Get Methods
    foreach (var item in mtd)
        Console.WriteLine("-->{0}", item.Name);
}

What’s the difference between public, protected and private?

  • Public: Any public member can be accessed from outside the class.

  • Protected: Protected access specifier allows a child class to access the member variables and member functions of its base class.

  • Private: Only functions of the same class can access its private members.

What’s Scaffolding?

ASP.NET Scaffolding is a code generation framework for ASP.NET Web applications. Visual Studio 2013 includes pre-installed code generators for MVC and Web API projects. You add scaffolding to your project when you want to quickly add code that interacts with data models.

What are Partial Methods in C#

Basically, partial methods exist in the partial class, or in the struct. A partial method may or may not contain implementation if a partial method doesn’t contain an implementation in any part then the compiler will not create that method in the final class or driver class.

partial void Method()
{
    // Code here
}

Choosing Between Class and Struct

As a rule of thumb, the majority of types in a framework should be classes. There are, however, some situations in which the characteristics of a value type make it more appropriate to use structs.

✔️ CONSIDER defining a struct instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.

❌ AVOID defining a struct unless the type has all of the following characteristics:

  • It logically represents a single value, similar to primitive types (int, double, etc.).

  • It has an instance size under 16 bytes.

  • It is immutable.

  • It will not have to be boxed frequently.

What is the difference between Class and Structure 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.

// C# program to illustrate the 
// concept of class 
using System; 
  
// Class Declaration 
public class Author { 
  
    // Data members of class 
    public string name; 
    public string language; 
    public int article_no; 
    public int improv_no; 
  
    // Method of class 
    public void Details(string name, string language, 
                        int article_no, int improv_no) 
    { 
        this.name = name; 
        this.language = language; 
        this.article_no = article_no; 
        this.improv_no = improv_no; 
  
        Console.WriteLine("The name of the author is :  " + name 
                          + "\nThe name of language is : " + language 
                          + "\nTotal number of article published  " 
                          + article_no + "\nTotal number of Improvements:"
                          +" done by author is : " + improv_no); 
    } 
  
    // Main Method 
    public static void Main(String[] args) 
    { 
  
        // Creating object 
        Author obj = new Author(); 
  
        // Calling method of class 
        // using class object 
        obj.Details("Ankita", "C#", 80, 50); 
    } 
} 

Output:

The name of the author is :  Ankita
The name of language is : C#
Total number of article published  80
Total number of Improvements: done by author is : 50

Last updated