Sunteți pe pagina 1din 10

Will the following code compile and run? string str = null; Console.WriteLine(str.

Length); The above code will compile, but at runtime System.NullReferenceException will be thrown. How do you create empty strings in C#? Using string.empty as shown in the example below. string EmptyString = string.empty; What is the difference between System.Text.StringBuilder and System.String? 1. Objects of type StringBuilder are mutable where as objects of type System.String are immutable. 2. As StringBuilder objects are mutable, they offer better performance than string objects of type System.String. 3. StringBuilder class is present in System.Text namespace where String class is present in System namespace. How do you determine whether a String represents a numeric value? To determine whether a String represents a numeric value use TryParse method as shown in the example below. If the string contains nonnumeric characters or the numeric value is too large or too small for the particular type you have specified, TryParse returns false and sets the out parameter to zero. Otherwise, it returns true and sets the out parameter to the numeric value of the string. string str = "One"; int i = 0; if(int.TryParse(str,out i)) { Console.WriteLine("Yes string contains Integer and it is " + i); } else { Console.WriteLine("string does not contain Integer"); } What is the difference between int.Parse and int.TryParse methods? Parse method throws an exception if the string you are trying to parse is not a valid number where as TryParse returns false and does not throw an exception if parsing fails. Hence TryParse is more efficient than Parse.

What is the difference between Convert.toString and .toString() method ? Just to give an understanding of what the above question means seethe below code. int i =0; MessageBox.Show(i.ToString()); MessageBox.Show(Convert.ToString(i));86 We can convert the integer i using i.ToString() or Convert.ToString so whats the difference. The basic difference between them is Convert function handles NULLS while i.ToString() does not it

will throw a NULL reference exception error. So as good coding practice using convert is always safe.
17. Explain the three services model commonly know as a three-tier application. Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources).

1) 2)you

an can

object not

of declare

an an

abstract abstract

class method

can outside

never the

be abstract

created. class.

3)can not be declared sealed. 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# }

You cannot achieve function overloading by changing the return type of the function.
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 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. public void multiply(int a, int b, out int prod) { prod = a * b; } 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


static int totalruns(params int[] runs) { int score = 0; for(int x=0; x &nsbp;score+=runs[x]; return score; } 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. How is method overriding different from overloading? When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class. What happens in memory when Box and Unbox a value-type? Boxing converts a value-type to a reference-type, thus storing the object on the heap. Unboxing converts a reference-type to a value-type, thus storing the value on the stack. What types of object can I throw as exceptions? Only instances of the System.Exception classes, or classes derived from System.Exception. This is in sharp contrast with C++ where instances of almost any type can be thrown. How can I check the type of an object at runtime? You can use the is keyword. For example: Can I get the name of a type at runtime? Yes, use the GetType method of the object class (which all types inherit from). Can you declare an override method to be static if the original method is not static? No. The signature of the virtual method must remain the same. (Note: Only the keyword virtual is changed to keyword override) What are the different ways a method can be overloaded? Different parameter data types, different number of parameters, different order of parameters. Whats a delegate? A delegate object encapsulates a reference to a method. 8. Whats a multicast delegate? A delegate that has multiple handlers assigned to it. Each assigned handler (method) is called.

Can you change the value of a variable while debugging a C# application? Yes. If you are debugging via Visual Studio.NET, just go to Immediate window. Whats an abstract class? A class that cannot be instantiated. An abstract class is a class that must be inherited and have the methods overridden. An abstract class is essentially a blueprint for a class without any implementation. What is an interface class? Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes. Can you declare the override method static while the original method is non-static? No, you cant, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override
What is File Mode? Types Of file mode? What is Pointer? Which one is most useful in Structure or Union? Answer:The meaning of file mode means in which mode we want to open the file.types of modes are read mode,write mode.pointer is the variable which holds the address of another variable.union r useful bcoz of memory no wastage but structures are frequently used than unions. About System.IO Name Space Answer. The classes in the namespace System.IO provides various methods to retrieve and changes information about Files as well as Directories . In C#, to perform a file I/O operation, you can use the same familiar basics of creating, opening, closing, reading, and writing using .NET Framework equivalent classes and methods How to use C# Directory Class Answer: Directory class in CSharp exposes methods to create , delete , move etc. operations to directories and subdirectories . Because of the static nature of C# Directory class , we do not have to instantiate the class. We can call the methods in the C# Directory class directly from the Directory class itself. How to use C# FileStream Class Answer: The FileStream Class represents a File in the Computer. Use the FileStream class to read from, write to, open, and close files on a file system, as well as to manipulate other file related operating system handles including pipes, standard input, and standard output. FileStream allows to move data to and from the stream as arrays of bytes. We operate File using FileMode in FileStream Class.

How to use C# Textreader Class Answer: Textreader and TextWriter are the another way to read and write file respectively, even though these are not stream classes. Textreader represents a reader that can read a sequential series of characters. The StreamReader and StreamWriter classes are derived from TextReader and TextWriter classes respectively, which read characters from streams and strings.

using System; using System.IO; class Test { public static void Main() { string path = @"c:\temp\MyTest.txt"; if (!File.Exists(path)) { // Create a file to write to. using (StreamWriter sw = File.CreateText(path)) { sw.WriteLine("Hello"); sw.WriteLine("And"); sw.WriteLine("Welcome"); } } // Open the file to read from. using (StreamReader sr = File.OpenText(path)) { string s = ""; while ((s = sr.ReadLine()) != null) { Console.WriteLine(s); } } try {

string path2 = path + "temp"; // Ensure that the target does not exist. File.Delete(path2); // Copy the file. File.Copy(path, path2); Console.WriteLine("{0} was copied to {1}.", path, path2); // Delete the newly created file. File.Delete(path2); Console.WriteLine("{0} was successfully deleted.", path2);

} catch (Exception e) { Console.WriteLine("The process failed: {0}", e.ToString()); }

Which is the base class for .net Class library? Ans: system.object

Define Strong Name. How do you apply a strong name to assembly?

A strong name means generating public key in order to provide unique name to the assembly. The name is used to provide global name to the assembly and allows it to be shared amongst several different applications. The key generated include assembly's name, the version number, the developer's identity, and a hash number. The developer's identity identifies the author of the assembly. The hash checks if the assembly is tempered since it is created. The key pair that defines the strong name is created using the Strong Name utility, Sn.exe. To sign an assembly with a strong name Create Key pair using the Strong Name utility, Sn.exe. Open the AssemblyInfo file of your project. Use the AssemblyKeyFileAttribute to specify the path to the key file for your project. Build your assembly. The strong name will be generated and signed to the assembly.

What is ILDASM? The contents of an assembly may be viewed using the ILDASM tool, that comes with the .NET SDK or the Visual Studio.NET. The ildasm.exe tool may also be used in the command line compiler.
Net - What does an assembly contain? An assembly contains following information: Assembly manifest: Information about the assembly. Type metadata: Information about the types. IL Code Resource files.

What are Satellite Assemblies?

Satellite assemblies provide an application the multilingual support. Satellite assemblies contain alternate sets of resources to be used in the application for different cultures

What do you understand by side-by-site execution of assembly?

This means multiple version of same assembly to run on the same computer. This feature enables to deploy multiple versions of the component

How do you create a resource-only assembly?

Resources are nonexecutable data in an application and the data can be updated without recompiling application. Resource assemblies can be created as follows: Add resource files to an empty project. Built the project. The resource will get compiled into assembly.

Explain how to retrieve resources using ResourceManager class.

ResourceManager class is used to retrieve resources at run time. Create a ResourceManager with resource file name and the resource assembly as parameters.

After having created, you can use ResourceManager.GetString method to retrieve a string. Use the ResourceManager.GetObject method to retrieve images and objects from a resource file

Define Global Assembly Cache.

Global Assembly Cache is the place holder for shared assembly. If an assembly is installed to the Global Assembly Cache, the assembly can be accessed by multiple applications. In order to install an assembly to the GAC, the assembly must have to be signed with strong name.

How do you install assembly to the Global Assembly Cache?

Followings are the steps to install assembly to the GAC. Sign assembly with a strong name using strong name utility, sn.exe. Open the AssemblyInfo file for your project. Use the AssemblyKeyFileAttribute to specify the path to the key file for your project. Build your assembly. Install the assembly to GAC by using gacutil utility e.g. gacutil -i abc.dll

What is the default access specifier in c#?Internal

modifier is specified.

is the default if no access

What is the default access modifier for the member?

C# Class variable Class method Structure variable Structure method Private Private Public Private

Briefly describe the two kinds of multidimensional arrays in .NET.

There are two types of multidimensional arrays: Rectangular arrays These multidimensional arrays have all the sub-arrays with a particular dimension of the same length. You need use a single set of square brackets for rectangular arrays. Jagged arrays These multidimensional arrays have each sub-array as independent arrays of different lengths. With these you need to use a separate set of square brackets for each dimension of the array.

What is the difference between Finalize() and Dispose()?

Dispose() is called by as an indication for an object to release any unmanaged resources it has held. Finalize() is used for the same purpose as dispose however finalize doesnt assure the garbage collection of an object. Dispose() operates determinalistically due to which it is generally preferred.

How to achieve polymorphism in C#.NET?

Polymorphism is when a class can be used as more than one type through inheritance. It can be used as its own type, any base types, or any interface type if it implements interfaces. It can be achieved in the following ways: Derived class inherits from a base class and it gains all the methods, fields, properties and events of the base class. To completely take over a class member from a base class, the base class has to declare that member as virtual.

How to add a ReadOnly property in C#.NET?

Properties can be made read-only by having only a get accessor in the implementation. public class X { public X(int id) { x_id = id; } public int ID { get { return x_id; } } }

scenario to use abstract class or interface

1. If you do not have any default implementation then go for Interfaces. If you have any default or standard code for the methods then go for Abstract class as it can accept partial implementation. 2. In future if you plan to inherit from multiple inheritance then go for interface. Abstract class do not allow multiple implementation. 3. If you want to restrict the accessbility of the methods that is defined then go for Abstract class as it can contain access modifiers for the subs, functions, properties.
String VS String builder

What is the Exact Difference?

First we will look at what happens when you concatenate two strings. For a rough idea, think like this. In a loop, you are adding few numbers to get a string to give all the numbers.
Collapse | Copy Code

string returnNumber = ""; for(int i = 0; i<1000; i++) { returnNumber = returnNumber + i.ToString(); }

Here we are defining a string called returnNumber and after that, in the loop we are concatenating the old one with the new to get a string. Do you know when we do like that we are assigning it again and again? I mean it's really like assigning 999 new strings! Actually the concatenation will create a new string returnNumber, with both old
returnNumber and i.ToString(). If we think roughly, how will the performance of the

code be? Can you imagine it? No one thinks about this when coding. If we can have something which is to be defined only once and add all the strings into it, what can you say about the performance. That's what StringBuilder does.
Collapse | Copy Code

StringBuilder returnNumber = new StringBuilder(10000); for(int i = 0; i<1000; i++) { returnNumber.Append(i.ToString()); }

We are creating a StringBuilder of length 10000 in memory where we can add all the
strings. This surely won't create a new string each and every time. Actually we are

creating a StringBinder, and whenever something is added it will get copied into that memory area. At the end, we can get the string by StringBuilder.ToString(). Here also, it won't create a new string. It will return a string instance that will point to the
string inside the StringBuilder. See, how efficient this is?

To explain this in a practical manner, I'm not going to analyze IL code or Optimized JIT compiled code. You can see the differences by running the samples.

Why String? Can't Use StringBinder Everywhere?

No. You can't. When initializing a StringBuilder, you are going down in performance. Also many actions that you do with string can't be done with StringBinder. Actually it is used mostly for situations as explained above. Last week, I showed a person who used
StringBuilder to just add two strings together! It's really nonsense. We must really

think about the overhead of initialization. In my personal experience, a StringBuilder can be used where more than four or more string concatenations take place. Also if you try to do some other manipulation (like removing a part from the string, replacing a part in the
string, etc.), then it's better not to use StringBuilder at those places. This is because we

are anyway creating new strings. Another important issue. We must be careful to guess the size of StringBuilder. If the size which we are going to get is more than what is assigned, it must increase the size. This will reduce its performance.
Static Class

Use a static class as a unit of organization for methods not associated with particular objects. Also, a static class can make your implementation simpler and faster because you do not have to create an object in order to call its methods. It is useful to organize the methods inside the class in a meaningful way, such as the methods of the Math class in the System namespace