General FAQs Part 2

Q:- What are Virtual and Hiding methods?

Ans:- Virtual Methods are used to be overridden in the derived classes. we cannot use the virtual modifier with the static, abstract, private, or override modifiers. Property can also be virtual except static properties. base keyword is used to call the base class overridden methods.
Hiding Methods are used to hide the base class method in the derived class.

class MyBaseClass
{
     public virtual string VirtualMethod()
     {
          return "This method is virtual and defined in MyBaseClass";
     }

     public string HideMethod()
     {
          return "This method is hidden and defined in MyBaseClass";
     }
}
class MyDerivedClass : MyBaseClass
{
     public override string VirtualMethod()
     {
          return "This method is override defined in MyDerivedClass";
     }

     public new string HideMethod()
     {
          return "This method is new defined in MyDerivedClass";
     }
}
public void Main()
{
     MyDerivedClass derivedClassObj = new myDerivedClass();
     Console.WriteLine(derivedClassObj.VirtualMethod());
     Console.WriteLine(derivedClassObj.HideMethod());
     MyBaseClass baseClassObj = derivedClassObj;
     Console.WriteLine(baseClassObj.VirtualMethod()); //calling derived class method
     Console.WriteLine(baseClassObj.HideMethod()); //calling base class method
}

Output: 
This method is override defined in MyDerivedClass
This method is new defined in MyDerivedClass
This method is override defined in MyDerivedClass
This method is hidden and defined in MyBaseClass

 

Q:- What are Sealed Classes and Methods?

Ans:- If class is declared as sealed, it means it can’t be inherit. In case of a method, this means that you can’t override the method.

sealed class FinalClass
{   // etc   }
class DerivedClass : FinalClass    //wrong. Will give compilation error
{    // etc  }

Declaring a method as a sealed servers a similar purpose as a class. In order to use the sealed keyword on method or property, it must be first overridden from a base class Otherwise don’t mark it as virtual in base class.

class MyClass : MyBaseClass
{
     public sealed override void FinalMethod()
     {  // etc  }
}
class DerivedClass : MyClass
{
     public override void FinalMethod()   //wrong. Will give compilation error
     { }
}
Advertisements

Key Points

P1 – C# doesn’t support multiple inheritance, however, multiple interface inheritance is allowed. Any class  or struct can inherit only one base class (abstract or user-defined) and multiple interfaces.

P2 – System.Object is the root base class and all other classes are by default derived from it if base class is not specified externally.

P3 – C# doesn’t allow abstract classes and interfaces to be instantiated. All members of interface are by default public.

P4 – If class inherit an interface then it should implement all the methods inside that interface otherwise compiler will through error. But in case of abstract classes if method is not marked abstract then inheriting class can skip the implementation of that method.

General FAQs Part 1

Q:- What is difference between const and readonly fields?

Ans:- Constant is used to declare to a variables whose value cannot be changed. Readonly also serves the same purpose but the value is not known until the runtime. Suppose we want to perform some calculation before we assign the value to variable. It is not possible in case of const. The rule to assign value to readonly variable is that it should be assigned inside the constructor not anywhere else. Also it is possible t0 have non-static readonly field in a class means for each instance of a class readonly field can have different value. Unlike const field, if we want a readonly field to be static, we have to declare it as such.

Q:- What is Anonymous Type?

Ans:- An anonymous type is simply a nameless class that inherits from object. Anonymous types can be created with the use of var variable. Declaration of var look like this:

var captain = new {FirstName = “Ron”, LastName = “Jones”};

This would create a new object with FirstName and LastName properties. The actual type of these new objects is unknown.

Q:- What is difference between Structs and Classes?

Ans:-
1. Structs are value type and classes are reference type.
2. Instance of classes stored in managed heap whereas structs stored either in stack or inline (if they are part of another object that is stored in heap).
3. Structs do no support inheritance whereas classes do.
4. Structs has default no-parameter constructor, which we are not allowed to replace. In classes we can have any constructor.
5. Classes are derived from System.Object (if base class is not specified) whereas a struct is always derived from System.ValueType. which in turn derives from System.Object.
6. Structs can be instantiated without using the new operator but classes can’t.

class TheClass
{
    public int x;
}
TheClass theClass; //object is declared but not initialized
theClass.x = 10; // throw exception

struct TheStruct
{
    public int x;
}
TheStruct theStruct; //default constructor is called
theStruct.x = 10;

 

Q:- What are Extension Methods?

Ans:- Extension methods are a way to extend the functionality of a class in cases source code is not available. Otherwise, inheritance is the great way to add functionality to objects. Extensions methods are static methods that can appear to be part of class without actually being in the source code of class.
Example:- Assume we have a class Money need a method AddToMoney(int amountToAdd). To do this create a static class and add the AddToMoney method as a static method. Here is what the code would look like:

public static class MoneyExtension
{
  public static void AddToMoney(this Money money, int amountToAdd) //notice the first parameter
  {
      money.Amount += amountToAdd;
  }
}

First parameter is the type that is being extended preceded by the this keyword. This is what tells the compiler that this method is part of Money type. To use the new method, we can make call just like any other method:

Money money = new Money(); //even though the extension method is static, standard instance method is used
money.AddToMoney(100); //notice first parameter doesn't appear

 

Q:- What are Nullable Type variables?

Ans:- Nullable types can represent all the values of an underlying type, and an additional nullvalue. Nullable types are declared in one of two ways:
System.Nullable variable
-or-
T? variable
T is the underlying type of the nullable type. T can be any value type including struct; it cannot be a reference type.

For an example of when you might use a nullable type, consider how an ordinary Boolean variable can have two values: true and false. There is no value that signifies “undefined”. In many programming applications, most notably database interactions, variables can exist in an undefined state. For example, a field in a database may contain the values true or false, but it may also contain no value at all. Similarly, reference types can be set to null to indicate that they are not initialized.

int? x = 10;
if (x.HasValue)
{
    System.Console.WriteLine(x.Value);
}
else
{
    System.Console.WriteLine("Undefined");
}

Explicit Conversion: A nullable type can be cast to a regular type, either explicitly with a cast, or by using the Value property.
Implicit Conversion: The conversion from an ordinary type to a nullable type, is implicit.

int? n = null;
//int m1 = n;      // Will not compile.
int m2 = (int)n;   // Compiles, but will create an exception if x is null.
int m3 = n.Value;  // Compiles, but will create an exception if x is null.
n = 10;  // Implicit conversion.

The ?? (Null Coalescing) Operator: The ?? operator defines a default value that is returned when a nullable type is assigned to a non-nullable type. This operator can also be used with multiple nullable types.

int? c = null;
int? e = null;
// d = c, unless c is null, in which case d = -1.
int d = c ?? -1;
// g = e or c, unless e and c are both null, in which case g = -1.
int g = e ?? c ?? -1;

 

Q:- What is is and as Operator?

Ans:- The is operator checks whether an object is compatible with the given type or not and returns a boolean result. The object may either be of same type or may be derived from that particular given type.
The as operator converts the reference types explicitly into a specific type. If the reference type is compatible with the specified type, it performs the successful conversion; otherwise, it returns the null vlaue. Note as operator doesn’t throw an exception.

object i = 25;
bool bFlag = i is string; //return false as i is of integer type
object str = "Hello World";
string str1 = i as string; //return null as casting i to string fails
string str2 = str as string; // return Hello World as successful casting str to string type

Predefined Data Types

There are two categories of data types in C#.

1. Value Type: Directly store the value. Stored in a memory known as the stack. Predefined value types are integer types, floating-point types. decimal type, boolean type, character type.

2. Reference Type: Store the reference of a value. Stored in a memory known as the managed heap. Predefined reference types supported in C# are object (CTS Type – System.Object) and string (CTS Type – System.String).

Common Type System (CTS) Types is the standard that specifies how type definition and specific value of Types are represented in computer memory. It is intended to allow program to be written in different programming language to easily share information. a Type can be described as a definition of a set of values (for example, “all integers between 0 and 10”), and the allowable operations on those values (for example, addition and subtraction).

Boxing and unboxing

Boxing converting value types to reference types is known as boxing.Boxing is of two types: Implicit and Explicit.

Example :-
Int32 X = 10;
Object O = X; //Implicit boxing
//Object O = (Object) X; //Explicit boxing
Console.WriteLine("The Object O = {0}", O); //prints out 10

Unboxing mean unbox a reference type back to value type. Unboxing require a explicit cast.

Example:-
Int32 X = 10;
Object O = X; // Implicit Boxing
X = (Int) O; //Explicit Unboxing

Truth of string type: Despite the style of assignment, string is a reference type. A string object is allocated on the heap, not the stack, and when we assign one string variable to the another string, we get two references to the same string in memory. However, with strings there are some difference from the usual behavior for reference types. For example: strings are immutable. You make changes to one of these strings, this will create an entirely new string object, leaving the other string unchanged.

using System;
class StringExample
{
   string s1 = "a string";
   string s2 = s1;
   Console.WriteLine("s1 is " + s1);
   Console.WriteLine("s2 is " + s2);
   s1 = "another string";
   Console.WriteLine("s1 is now " + s1);
   Console.WriteLine("s2 is now " + s2);
   return 0;
}
Output: s1 is a string
        s2 is a string
        s1 is now another string
        s2 is now a string

Basic concepts of .NET Framework

.NET Framework is a software framework which primarily runs on Microsoft windows. It includes a large library and supports several programing languages which allows language interoperability. The .NET library is available to all the programming languages that .NET supports.

Common Language Runtime Engine (CLR) is the execution engine of .Net framework. All .Net programs runs under the supervision of the CLR, guaranteeing certain properties and behavior in the areas of memory management, security and exception handling.

Optional and Named Parameters

Optional parameters allow us to provide default values for some of the parameters of methods and allow type of overloading. Here’s an example:

public void CreateUser(string firstName, string lastName, bool isAdmin, bool isTrialUser) {}

If we want to overload this method and have default values for the two bool parameters, then we could have easily few more methods. Now with optional parameters, we are able to do something like this:

public void CreateUser(string firstName, string lastName, bool isAdmin = false, bool isTrialUser = true) {}

In above code, the parameters firstName and lastName do not have default value set, while isAdmin and isTrialUser do have default value set. As a consumer of this method, i can do some of the following:

myClass.CreateUser(“Jessica”,”Alba”); //isAdmin and isTrailUser set to default value set

myClass.CreateUser(“Jessica”,”Alba”, true); //isAdmin set to true and isTrialUser to default

myClass.CreateUser(“Jessica”,”Alba”, true, false);

myClass.CreateUser(“Jessica”,”Alba”, isTrialUser: false); //isAdmin set to default and isTrialUser to false

The last example makes use of named parameters. This new feature make code easier to read and understand. Look at below lines of code:

File.Copy(@”c:\myFile.txt”, @”c:\myOtherFile.txt”, true);

File.Copy(sourceFileName: @”myFile.txt”, destFileName: @”c:\myOtherFile.txt”, overwrite: true);

%d bloggers like this: