C Sharp Realtime Interview Questions and Answers:Part 3

Aired Consulting 10/28/2009 No Comment
Interview Questions and Answers for C sharp in companies like IBM,Accenture,Dell,Wipro Infosys,TCS,HP

What does the modifier protected internal in C# mean?
The Protected Internal can be accessed by Members of the Assembly or the inheriting class, and of course, within the class itself.

In VB.NET, the equivalent of protected internal is protected friend.
The access of this modifier is limited to the current assembly or the types derived from the defining class in the current assembly. To know more on different types of access specifiers
Can multiple data types be stored in System.Array?
So whats an array all about? An array is a collection of items of the same type, that is grouped together and encompassed within an array object. The array object, or the System.Array object to be precise, is derived from the System.Object class. It is thus, stored in the form of a heap in the memory.


An array may be of single dimensional, multi-dimensional or jagged (a jagged array means an array within an array).

A group of items when assigned values within braces implicitly derive from System.Array class. See example below written in C#...
int[] testIntArray = new int[4] { 2, 3, 4, 5 };
Object[] testObjArray = new Object[5] { 32, 22, 23, 69, 75 };
Ideally an array should contain a single data type. But still in case there is a requirement to place data of different data types in a specific array, then in such a scenario, the data elements should be declared as an object type. When this is done, then each element may point ultimately to a different data type. See code example below written in VB.NET...
Dim allTypes As Object() = New Object() {}

'In this kind of scenario, the performance may tend to slow down, as data conversions may take place.
'In case a value type is converted to reference type, then boxing and unboxing occurs
'To know more on Value Types & Reference Types, Click Here

Dim studentTable(2) As Object
studendTable(0) = "Vishal Khanna"
studentTable(1) = 28
studentTable(2) = #9/1/1978#

'To get these values of these varying datatypes, their values are converted to their original data type

Dim myAge As Integer = CInt(studentTable(1))
Dim myBirthDay as Date = CDate(studentTable(2))

How to sort array elements in descending order in C#?

Elements of an array may not be sorted by default. To sort them in descending order, the Sort() method is first called. Next, to descend the order, call the Reverse() method

Whats the use of "throw" keyword in C#?
The throw keyword is used to throw an exception programatically in C#. In .NET, there is an in-built technique to manage & throw exceptions. In C#, there are 3 keyword, that are used to implement the Exception Handling. These are the try, catch and finally keywords. In case an exception has to be implicitly thrown, then the throw keyword is used. See code example below, for throwing an exception programatically...
class SomeClass
{
public static void Main()
{
try
{
throw new DivideByZeroException("Invalid Division Occured");
}
catch(DivideByZeroException e)
{
Console.WriteLine("Exception - Divide by Zero" );
}
}
}

Can we put multiple catch blocks in a single try statement in C#?
Yes. Multiple catch blocks may be put in a try block. See code example below, to see multiple catch blocks being used in C#.
class ClassA
{
public static void Main()
{
int y = 0;
try
{
val = 100/y;
Console.WriteLine("Line not executed");
}
catch(DivideByZeroException ex)
{
Console.WriteLine("DivideByZeroException" );
}
catch(Exception ex)
{
Console.WritLine("Some Exception" );
}
finally
{
Console.WriteLine("This Finally Line gets executed always");
}
Console.WriteLine("Result is {0}",val);
}
}

How to achieve polymorphism in C#?
In C#, polymorphism may be achieved by overloading a function, overloading an operator, changing the order of types, changing the types using the same name for the member in context. To see some code examples of polymorphism, Click Here.

What is polymorphism?
Polymorphism means allowing a single definition to be used with different types of data (specifically, different classes of objects). For example, a polymorphic function definition can replace several type-specific ones, and a single polymorphic operator can act in expressions of various types. Many programming languages implement some forms of polymorphism.

The concept of polymorphism applies to data types in addition to functions. A function that can evaluate to and be applied to values of different types is known as a polymorphic function. A data type that contains elements of different types is known as a polymorphic data type.

Polymorphism may be achieved by overloading a function, overloading an operator, changing the order of types, changing the types using the same name for the member in context.
Example:
Public Class Calc
{
public void fnMultiply(int x, int y)
{ return x * y; }
public void fnMultiply(int x, int y, int z)
{ return x * y * z; }
}
...
...
Calc obj;
int Result;
Result = obj.fnMultiply(2,3,4); // The second fnMultiply would be called
Result = obj.fnMultiply(3,4); // The first fnMultiply would be called
//Here, the call depends on the number of parameters passed, polymorphism is achieved using overloading

How to add a ReadOnly property in C#?
Property - A property is an entity that describes the features of an object. A property is a piece of data contained within a class that has an exposed interface for reading/writing. Looking at that definition, you might think you could declare a public variable in a class and call it a property. While this assumption is somewhat valid, the true technical term for a public variable in a class is a field. The key difference between a field and a property is in the inclusion of an interface. We make use of Get and Set keywords while working with properties. We prefix the variables used within this code block with an underscore. Value is a keyword, that holds the value which is being retrieved or set. See code below to set a property as ReadOnly. If a property does not have a set accessor, it becomes a ReadOnly property.

public class ClassA
{
private int length = 0;
public ClassA(int propVal)
{
length = propVal;
}
public int length
{
get
{
return length;
}
}
}

How to prevent a class from being inherited? Sealed in C#?
In order to prevent a class in C# from being inherited, the sealed keyword is used. Thus a sealed class may not serve as a base class of any other class. It is also obvious that a sealed class cannot be an abstract class. Code below...
sealed class ClassA
{
public int x;
public int y;
}
No class can inherit from ClassA defined above. Instances of ClassA may be created and its members may then be accessed, but nothing like the code below is possible...
class DerivedClass: ClassA {} // Error

Can we inherit multiple interfaces in C#?
Yes. Multiple interfaces may be inherited in C#.

Note that when a class and multiple interfaces are to be inherited, then the class name should be written first, followed by the names of the interfaces. See code example below, on how to inherit multiple interfaces in C#.
class someclass : parentclass, IInterface1, IInterface2
{
//...Some code in C#
}

What are the different ways of overloading methods in C#?

What is function overloading in C#?

Before knowing the different methods of overloading in C#, lets first clear out what exactly overloading is. Overloading is the OOPs concept of using a method or a class in different styles by modifying the signature of the parameters in it. To know more on overloading, Click Here.

In order to achieve overloading, there may be several techniques applied. There are different types of overloading like Operator Overloading, Function Overloading etc.

Function overloading may be achieved by changing the order of parameters in a function, by changing the types passed in the function, and also by changing the number of parameters passed in a function. See code sample below to see types of overloading.
//Define a method below
public void fnProcess(int x, double y)
{
......
}
//change the order of parameters
public void fnProcess(double x, int y) {
//.......Some code in C#
}
//Similarly, we may change the number of parameters in fnProcess
//and alter its behaviour

How to call a specific base constructor in C#?

What is a Constructor? - It is a method that gets invoked when an instance of a class is created. In case a class has plenty of constructors, i.e. there are plenty of overloaded constructors, in such a scenario, it is still possible to invoke a specific base constructor. But there is a special way, as explicit calls to a base constructor is not possible in C#. See code below:
public class dotnetClass
{
public dotnetClass()
{
// The constructor method here
}
// Write the class members here
}

//Sample code below shows how to overload a constructor
public class dotnetClass
{
public dotnetClass()
{
// This constructor is without a parameter
// Constructor #1
}

public dotnetClass(string name)
{
// This constructor has 1 parameter.
// Constructor #2

}
}
This constructor gets executed when an object of this class is instantiated. This is possible in C#. Calling a specific constructor will depend on how many parameters, and what parameters match a specific constructor. Note that a compile time error may get generated when 2 constructors of the same signature are created.

We may make use of the this keyword and invoke a constructor. See code example below.
this("some dotnet string");
//This will call Constructor #2 above

What is the use of the base keyword.
Suppose we have a derived class named dotnetderivedclass. If this derived class is to invoke the constructor of a base class, we make use of the base keyword. See code example below on how to use a base keyword to invoke the base class constructor.
public class dotnetClass
{
public dotnetClass()
{
// The 1st base class constructor defined here
}

public dotnetClass(string Name)
{
// The 2nd base class constructor defined here
}
}

public class dotnetderivedclass : dotnetClass
// A class is being inherited out here
{
public dotnetderivedclass()
{
// dotnetderivedclass 1st constructor defined here
}

public dotnetderivedclass(string name):base(name)
{
// dotnetderivedclass 2nd constructor defined here
}
}

Note that we have used the base keyword in the sample code above. The sequence of execution of the constructors will be as follows:
public dotnetClass() method -> public dotnetderivedclass() method

The above sequence triggers when there is no initializer to the base class, and thus it triggers the parameterless base class constructor. The other base class constructor may also get invoked when we pass a parameter while defining it.

What is a static constructor?

Static Constructor
- It is a special type of constructor, introduced with C#. It gets called before the creation of the first object of a class(probably at the time of loading an assembly). See example below.
Example:
public class SomeClass()
{
static SomeClass()
{
//Static members may be accessed from here
//Code for Initialization
}
}
While creating a static constructor, a few things need to be kept in mind:
* There is no access modifier require to define a static constructor
* There may be only one static constructor in a class
* The static constructor may not have any parameters
* This constructor may only access the static members of the class
* We may create more than one static constructor for a class

Can a class be created without a constructor?
No. In case we dont define the constructor, the class will access the no-argument constructor from its base class. The compiler will make this happen during compilation.

What are generics in C#?
Generics in C# is a new innovative feature through which classes and methods in C# may be designed in such a way that the rules of a type are not followed until it is declared. The generics feature in C# has been introduced with version 2.0 of the .NET Framework. Using generics, a class template may be declared that may follow any type as required at runtime. The class behavior is later governed by the type that we pass to the class. Once the type is passed, the class behaves depending on the type passed to this generic class.
Related Posts

No comments:

 

Aired | Copyright © 2009-2014| All Rights Reserved 2014 | Privacy Policy and Disclaimer

Contact Us | About Us