Skip to main content

C# FAQ #1

C#FAQ #1

Collected from the Internet:

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.

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
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…

   1: class SomeClass
   2: {
   3:     public static void Main()
   4:     {
   5:          try
   6:          {
   7:              throw new DivideByZeroException("Invalid Division Occured");
   8:          }
   9:          catch(DivideByZeroException e)
  10:          {
  11:                Console.WriteLine("Exception - Divide by Zero" );
  12:          }
  13:     }
  14: } 

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#.

   1: class ClassA
   2: {
   3:     public static void Main()
   4:     {
   5:         int y = 0;
   6:         try
   7:         {
   8:             val = 100/y;
   9:             Console.WriteLine("Line not executed");
  10:         }
  11:         catch(DivideByZeroException ex)
  12:         {
  13:             Console.WriteLine("DivideByZeroException" );
  14:         }
  15:         catch(Exception ex)
  16:         {
  17:             Console.WritLine("Some Exception" );
  18:         }
  19:         finally
  20:         {
  21:             Console.WriteLine("This Finally Line gets executed always");
  22:         }
  23:         Console.WriteLine("Result is {0}",val);
  24:     }
  25: } 

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.When a class derives features of another class, this feature is called Inheritance.

Compare Session state and Viewstate in .NET?

Session state is the feature of ASP.NET based web applications using which values of a variable may be persisted and then posted to another page.

Viewstate property of a page or a control, or a viewstate object for a variable value, may also be created to persist its value across a postback. However, the viewstate value are for page level, i.e. they cannot be posted across to another page.

The datagrid or the gridview has a property called AutoGenerateColumns. Make this property false. Once false, the columns may then be added to the gridview manually.

How to add gridview/datagrid columns manually? Autogenerate in .NET?

The datagrid (of ASP.NET 1.1) and gridview (of ASP.NET 2.0) has a property called AutoGenerateColumns. This property is set to false. After this, columns may be set manually. Sample source below…

   1: <asp:GridView ID="GridView1" DataSourceID="SqlDataSource1" AutoGenerateColumns="False" runat="server">
   2: <Columns>
   3: <asp:BoundField HeaderText="ID" DataField="au_id" ReadOnly="true" />
   4: <asp:BoundField HeaderText="Last Name" DataField="au_lname" />
   5: <asp:BoundField HeaderText="First Name" DataField="au_fname" />
   6: <asp:BoundField HeaderText="Phone" DataField="phone" />
   7: <asp:BoundField HeaderText="Address" DataField="address" />
   8: Columns>
   9: asp:GridView>
  10: <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
  11: SelectCommand="SELECT [au_id], [au_lname], [au_fname], [phone], [address] FROM [authors]"
  12: ConnectionString="<%$ ConnectionStrings:Pubs %>" />

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.

   1: public class ClassA
   2: {
   3:     private int length = 0;
   4:     public ClassA(int propVal)
   5:     {
   6:         length = propVal;
   7:     }
   8:     public int length
   9:     {
  10:         get
  11:         {
  12:             return length;
  13:         }
  14:     }
  15: }

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…

   1: sealed class ClassA
   2: {
   3:     public int x; 
   4:     public int y;
   5: }

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#.

   1: class someclass : parentclass, IInterface1, IInterface2
   2: {
   3:     //...Some code in C#
   4: }

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. 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.

   1: //Define a method below
   2: public void fnProcess(int x, double y)
   3: {
   4:     ......
   5: }
   6: //change the order of parameters
   7: public void fnProcess(double x, int y) {
   8:     //.......Some code in C#
   9: }
  10: //Similarly, we may change the number of parameters in fnProcess 
  11: //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:

   1: public class dotnetClass
   2: {
   3:     public dotnetClass()
   4:     {
   5:         // The constructor method here
   6:     }
   7:     // Write the class members here
   8: }
   9:  
  10: //Sample code below shows how to overload a constructor
  11: public class dotnetClass
  12: {
  13:     public dotnetClass()
  14:     {
  15:         // This constructor is without a parameter
  16:         // Constructor #1 
  17:     }
  18:     public dotnetClass(string name)
  19:     {
  20:         // This constructor has 1 parameter.
  21:         // Constructor #2
  22:     }
  23: }

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.

   1: public class dotnetClass
   2: {
   3:     public dotnetClass()
   4:     {
   5:         // The 1st base class constructor defined here
   6:     }
   7:     public dotnetClass(string Name)
   8:     {
   9:         // The 2nd base class constructor defined here
  10:     }
  11: }
  12:  
  13: public class dotnetderivedclass : dotnetClass
  14: // A class is being inherited out here
  15: {
  16:     public dotnetderivedclass()
  17:     {
  18:         // dotnetderivedclass 1st constructor defined here
  19:     }
  20:     public dotnetderivedclass(string name):base(name)
  21:     {
  22:         // dotnetderivedclass 2nd constructor defined here
  23:     }
  24: } 

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 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.

More on generics in C-Sharp, read this article Click Here.

What is the use of the main() function in C#?

Every executable C# application must contain a class defining a Main() method that signifies the entry point of the application. Note that the Main() method is of the access type public by nature. Moreover, it is also static. See example below:

using System;

   1: class Question 
   2: {
   3:     public static int Main(string[] args)
   4:     {
   5:         Console.Writeline("Another Question");
   6:         Console.Readline();
   7:         return 0;
   8:     }
   9: }

A public member is accessible from other types. The main() method is set as static so that it may be invoked at class level itself, without the need of creating an instance of it. The single parameter is an array of strings. that may contain any number of incoming command line arguments.

Are C# Keywords in lowercase or uppercase?

All C# keywords are in lowercase.

Namespaces, Types and Members have their first character in uppercase.

What is the use of Console.Readline() in C#?

Using the Console.Readline() method means that the command prompt launched by Visual Studio remains visible during an application session until the ENTER key is pressed by the user.

Can we set the specifier of the main() method in C# as private?

Yes. When the access specifier is set as private for the Main() method, then other assemblies may not invoke this class’ Main() method as the starting point of the application. The startup scope gets limited to the class in context itself. See code below:

   1: private static void Main()
   2: {
   3:     //This code isn't invoked automatically by other assemblies
   4: }

Can we set different types of parameters & return-types in main() method"?

Yes. The Main() method may easily be played around with by developers by passing different parameters and setting different return types. See the code below, that demonstrates different ways the Main() method may be implemented:

   1: // (1)
   2: public static void Main(string[] args)
   3: {
   4:     //NO return type, the argument is an array of strings
   5: }
   6:  
   7: // (2)
   8: public static int Main(string[] args)
   9: {
  10:     //Return type is int, argument is an array of strings
  11: }
  12:  
  13: // (3)
  14: public static int Main()
  15: {
  16:     //Return type is int, NO arguments
  17: }
  18:  
  19: // (4)
  20: public static void Main()
  21: {
  22:     //Return type is void, NO arguments
  23: }

What is the use of GetCommandLineArgs() method?

The GetCommandLineArgs() method is used to access the command line arguments. The return value of this method is an array of strings. It is a method of the System.Environment class. See the code example below:

   1: public static int Main(string[] args)
   2: {
   3:     string[] strArgs = System.Environment.GetCommandLineArgs();
   4:     Console.WriteLine("Arguments {0}", strArgs[0]);
   5: }

What is the use of System.Environment class?

The class System.Environment is used to retrieve information about the operating system. Some of the static members of this class are as follows:

1) Environment.OSVersion – Gets the version of the operating system

2) Environment.GetLogicalDrives() – method that returns the drives

3) Environment.Version – returns the .NET version running the application

4) Environment.MachineName – Gets name of the current machine

5) Environment.Newline – Gets the newline symbol for the environment

6) Environment.ProcessorCount – returns number of processors on current machine

7) Environment.SystemDirectory – returns complete path to the System Directory

8) Environment.UserName – returns name of the entity that invoked the application

Why is the new keyword used for instantiating an object in .NET?

The new keyword instructs the .NET compiler to instantiate a new object, with appropriate number of bytes (depending on the type) for the object and gather required memory from the managed heap.

What are the default values for bool, int, double, string, char, reference-type variables?

When the objects of the following types are declared, then they have a default value during declaration. The following table shows the default value for each type:

Type

Default Value

bool

false

int

0

double

0

string

null

char

‘\0′

Reference Type

null

Why does the compiler throw an error when variables are declared with an initial value?

The compiler throws an error when a variable is declared without an initial value, when the declaration is within a member scope. The variables do not recieve default value when they are declared within a scope.

Note that if the variable is used as an output parameter, this variable does not need to be assigned an initial value.

How to declare a constant variable in C#? What is the use of the const keyword?

If a variable needs to have a fixed value, that may not be changed across the application’s life, then it may be declared with the const keyword. The value assigned to a constant variable (using the const keyword) must be known at the time of compilation.

In C#, can we create an object of reference type using const keyword?

No. A constant member may not be created of an object that is of reference type, because its value is decided dynamically at runtime.

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

When using the const keyword to set a constant variable, the value needs to be set at compile time. The const keyword may not be used with an object of reference type.

In case a reference type needs to be assigned a non-changeable value, it may be set as readonly

What are the different parameter modifiers available in C#?

What is a parameter modifier?

Parameter modifiers in C# are entities that controls the behaviour of the arguments passed in a method. Following are the different parameter modifiers in C#:

1) None – if there is NO parameter modifier with an argument, it is passed by value, where the method recieves a copy of the original data.

2) out – argument is passed by reference. The argument marked with "out" modifier needs to be assigned a value within this function, otherwise a compiler error is returned.

   1: public void multiply(int a, int b, out int prod)
   2: {
   3:     prod = a * b;
   4: }

Here, note that prod is assigned a value. If not done so, then a compile time error is returned.

3) params- This modifier gives the permission to set a variable number of identical datatype arguments.

Note that a method may have only one "params" modifier. The params modifier needs to be in the last argument.

   1: static int totalruns(params int[] runs)
   2: {
   3:     int score = 0;
   4:     for(int x=0; x  
   5:     
   6:     return score;
   7: }

Further, from the calling function, we may pass the scores of each batsman as below…

score = totalruns(12,36,0,5,83,25,26);

4) ref – The argument is given a value by the caller, where data is passed by reference. This value may optionally be reset in the called method. Note that even if NO value is set in the called method for the ref attribute, no compiler error is raised.

What is the difference between out and ref in C#?

1) out parameters return compiler error if they are not assigned a value in the method. Not such with ref parameters.

2) out parameters need not be initialized before passing to the method, whereas ref parameters need to have an initial value before they are passed to a method.

Comments

Popular posts from this blog

SharePoint 2007 - Simple Task Dashboard

MERGE transformation in SSIS