Posts

Showing posts from May, 2009

Difference between array, arraylist, List, Hashtable, Dictionary and SortedList in c#

Basic difference is that arrays are of fixed size. Whereas an ArrayList implements the list data structure and can dynamically grow. While arrays would be more performance that a list, a list would be far more flexible since you don't need to know the required size initially. Array - represents an old-school memory array - kind of like a alias for a normal type[] array. Can enumerate. Can't grow automatically. I would assume very fast insertion, retrieve and speed. ArrayList - automatically growing array. Adds more overhead. Can enum., probably slower than a normal array but still pretty fast. These are used a lot in .NET List - one of my favorites - can be used with generics, so you can have a strongly typed array, e.g. List . Other than that, acts very much like ArrayList. Hashtable - plain old hashtable. O(1) to O(n) worst case. Can enumerate the value and keys properties, and do key/val pairs. Dictionary - same as above only strongly typed via generics, such a...

C#.net interview questions on strings

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

override the ToString() method

Why should you override the ToString() method? All types in .Net inherit from system.object directly or indirectly. Because of this inheritance, every type in .Net inherit the ToString() method from System.Object class. Consider the example below. using System; public class MainClass { public static void Main() { int Number = 10; Console.WriteLine(Number.ToString()); } } In the above example Number.ToString() method will correctly give the string representaion of int 10, when you call the ToString() method. If you have a Customer class as shown in the below example and when you call the ToString() method the output doesnot make any sense. Hence you have to override the ToString() method, that is inherited from the System.Object class. using System; public class Customer { public string FirstName; public string LastName; } public class MainClass { public static void Main() { Customer C = new Customer(); C.FirstName = "David"; C.LastName = "Boon"; Console.WriteLine(C....

C# Interview Questions on value types and reference types

What are the 2 types of data types available in C#? 1. Value Types 2. Reference Types If you define a user defined data type by using the struct keyword, Is it a a value type or reference type? Value Type If you define a user defined data type by using the class keyword, Is it a a value type or reference type? Reference type Are Value types sealed? Yes, Value types are sealed. What is the base class from which all value types are derived? System.ValueType Give examples for value types? Enum Struct Give examples for reference types? Class Delegate Array Interface What are the differences between value types and reference types? 1. Value types are stored on the stack where as reference types are stored on the managed heap. 2. Value type variables directly contain their values where as reference variables holds only a reference to the location of the object that is created on the managed heap. 3. There is no heap allocation or garbage collection overhead for value-type variables. As ...

C# Interview Questions on Properties

What are Properties in C#. Explain with an example? Properties in C# are class members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods. In the example below _firstName and _lastName are private string variables which are accessible only inside the Customer class. _firstName and _lastName are exposed using FirstName and LastName public properties respectively. The get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels. The value keyword is used to define the value being assigned by the set accessor. The FullName property computes the full name of the customer. Full Name property is readonly, because it has only the get accessor...

C# Interview Questions on structs

Will the following code compile? using System; public class Example { static void Main() { TestStruct T = new TestStruct(); Console.WriteLine(T.i); } } public struct TestStruct { public int i=10; //Error: cannot have instance field initializers in structs } No, a compile time error will be generated stating "within a struct declaration, fields cannot be initialized unless they are declared as const or static" Can a struct have a default constructor (a constructor without parameters) or a destructor in C#? No Can you instantiate a struct without using a new operator in C#? Yes, you can instantiate a struct without using a new operator Can a struct inherit from another struct or class in C#? No, a struct cannot inherit from another struct or class, and it cannot be the base of a class. Can a struct inherit from an interface in C#? Yes Are structs value types or reference types? Structs are value types. What is the base type from which all structs inherit directly? All structs i...

C# Interview Questions on polymorphism

Explain polymorphism in C# with a simple example? Polymorphism allows you to invoke derived class methods through a base class reference during run-time. An example is shown below. using System; public class DrawingObject { public virtual void Draw() { Console.WriteLine("I am a drawing object."); } } public class Triangle : DrawingObject { public override void Draw() { Console.WriteLine("I am a Triangle."); } } public class Circle : DrawingObject { public override void Draw() { Console.WriteLine("I am a Circle."); } } public class Rectangle : DrawingObject { public override void Draw() { Console.WriteLine("I am a Rectangle."); } } public class DrawDemo { public static void Main() { DrawingObject[] DrawObj = new DrawingObject[4]; DrawObj[0] = new Triangle(); DrawObj[1] = new Circle(); DrawObj[2] = new Rectangle(); DrawObj[3] = new DrawingObject(); foreach (DrawingObject drawObj in DrawObj) { drawObj.Draw(); } } } When can a derived class override ...

C# Interview Questions on Inheritance

What are the 4 pillars of any object oriented programming language? 1. Abstraction 2. Inheritance 3. Encapsulation 4. Polymorphism Do structs support inheritance? No, structs do not support inheritance, but they can implement interfaces. What is the main advantage of using inheritance? Code reuse Is the following code legal? class ChildClass : ParentClassA, ParentClassB { } No, a child class can have only one base class. You cannot specify 2 base classes at the same time. C# supports single class inheritance only. Therefore, you can specify only one base class to inherit from. However, it does allow multiple interface inheritance. What will be the output of the following code? using System; public class BaseClass { public BaseClass() { Console.WriteLine("I am a base class"); } } public class ChildClass : BaseClass { public ChildClass() { Console.WriteLine("I am a child class"); } static void Main() { ChildClass CC = new ChildClass(); } } Output: I am a base clas...

C# Interview Questions on Data Types

What are the 3 types of comments in C#? 1. Single Line Comments. You define single line comments with // as shown below. //This is an example for single line comment 2. Multi line comments. You define multi line comments with /* */ as shown below. /*This is an example for Multi Line comments*/ 3. XML Comments. You define XML comments with /// as shown below. ///This is an example for defining XML comments. Is C# a strongly-typed language? Yes What are the 2 broad classifications of data types available in C#? 1. Built in data types. 2. User defined data types. Give some examples for built in datatypes in C#? 1. int 2. float 3. bool How do you create user defined data types in C#? You use the struct, class, interface, and enum constructs to create your own custom types. The .NET Framework class library itself is a collection of custom types provided by Microsoft that you can use in your own applications.

C# Interview Questions on Fields

What are the 2 broad classifications of fields in C#? 1. Instance fields 2. Static fields What are instance fields in C#? Instance fields are specific to an instance of a type. If you have a class T, with an instance field F, you can create two objects of type T, and modify the value of F in each object without affecting the value in the other object. What is a static field? A static field belongs to the class itself, and is shared among all instances of that class. Changes made from instance A will be visible immediately to instances B and C if they access the field. Will the following code compile? using System; class Area { public static double PI = 3.14; } class MainClass { public static void Main() { Area A = new Area(); Console.WriteLine(A.PI); } } No, a compile time error will be generated stating "Static member 'Area.PI' cannot be accessed with an instance reference; qualify it with a type name instead". This is because PI is a static field. Static fields ca...

C# Interview Questions on data type casting

What do you mean by casting a data type? Converting a variable of one data type to another data type is called casting. This is also called as data type conversion. What are the 2 kinds of data type conversions in C#? Implicit conversions: No special syntax is required because the conversion is type safe and no data will be lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes. Explicit conversions: Explicit conversions require a cast operator. The source and destination variables are compatible, but there is a risk of data loss because the type of the destination variable is a smaller size than (or is a base class of) the source variable. What is the difference between an implicit conversion and an explicit conversion? 1. Explicit conversions require a cast operator where as an implicit converstion is done automatically. 2. Explicit conversion can lead to data loss where as with implicit conversions there is ...

C# Interview questions on Boxing and Unboxing

What is Boxing and Unboxing? Boxing - Converting a value type to reference type is called boxing. An example is shown below. int i = 101; object obj = (object)i; // Boxing Unboxing - Converting a reference type to a value typpe is called unboxing. An example is shown below. obj = 101; i = (int)obj; // Unboxing Is boxing an implicit conversion? Yes, boxing happens implicitly. Is unboxing an implicit conversion? No, unboxing is an explicit conversion. What happens during the process of boxing? Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object. Due to this boxing and unboxing can have performance impact.

C# Interview Questions on Constants

What are constants in C#? Constants in C# are immutable values which are known at compile time and do not change for the life of the program. Constants are declared using the const keyword. Constants must be initialized as they are declared. You cannot assign a value to a constant after it isdeclared. An example is shown below. using System; class Circle { public const double PI = 3.14; public Circle() { //Error : You can only assign a value to a constant field at the time of declaration //PI = 3.15; } } class MainClass { public static void Main() { Console.WriteLine(Circle.PI); } } Can you declare a class or a struct as constant? No, User-defined types including classes, structs, and arrays, cannot be const. Only the C# built-in types excluding System.Object may be declared as const. Use the readonly modifier to create a class, struct, or array that is initialized one time at runtime (for example in a constructor) and thereafter cannot be changed. Does C# support const methods, proper...

C# Interview Questions on Access Modifiers

What are Access Modifiers in C#? In C# there are 5 different types of Access Modifiers. Public The public type or member can be accessed by any other code in the same assembly or another assembly that references it. Private The type or member can only be accessed by code in the same class or struct. Protected The type or member can only be accessed by code in the same class or struct, or in a derived class. Internal The type or member can be accessed by any code in the same assembly, but not from another assembly. Protected Internal The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly. What are Access Modifiers used for? Access Modifiers are used to control the accessibilty of types and members with in the types. Can you use all access modifiers for all types? No, Not all access modifiers can be used by all types or members in all contexts, and in some cases the accessibility of a type member is constrained by the accessibilit...

Basic C# Interview Questions on strings

What is the difference between string keyword and System.String class? string keyword is an alias for Syste.String class. Therefore, System.String and string keyword are the same, and you can use whichever naming convention you prefer. The String class provides many methods for safely creating, manipulating, and comparing strings. Are string objects mutable or immutable? String objects are immutable. What do you mean by String objects are immutable? String objects are immutable means, they cannot be changed after they have been created. All of the String methods and C# operators that appear to modify a string actually return the results in a new string object. In the following example, when the contents of s1 and s2 are concatenated to form a single string, the two original strings are unmodified. The += operator creates a new string that contains the combined contents. That new object is assigned to the variable s1, and the original object that was assigned to s1 is released for garba...

Basic C# Interview Questions on classes and structs

What do you mean by saying a "class is a reference type"? A class is a reference type means when an object of the class is created, the variable to which the object is assigned holds only a reference to that memory. When the object reference is assigned to a new variable, the new variable refers to the original object. Changes made through one variable are reflected in the other variable because they both refer to the same data. What do you mean by saying a "struct is a value type"? A struct is a value type mean when a struct is created, the variable to which the struct is assigned holds the struct's actual data. When the struct is assigned to a new variable, it is copied. The new variable and the original variable therefore contain two separate copies of the same data. Changes made to one copy do not affect the other copy. When do you generally use a class over a struct? A class is used to model more complex behavior, or data that is intended to be modified aft...

Basic C# Interview Questions on arrays

What is an array? An array is a data structure that contains several variables of the same type. What are the 3 different types of arrays? 1. Single-Dimensional 2. Multidimensional 3. Jagged What is Jagged Array? A jagged array is an array of arrays. Are arrays value types or reference types? Arrays are reference types. What is the base class for Array types? System.Array Can you use foreach iteration on arrays in C#? Yes,Since array type implements IEnumerable , you can use foreach iteration on all arrays in C#.

Abstract and Sealed Class Members

What is an abstract class? An abstract class is an incomplete class and must be implemented in a derived class. Can you create an instance of an abstract class? No, abstract classes are incomplete and you cannot create an instance of an abstract class. What is a sealed class? A sealed class is a class that cannot be inherited from. This means, If you have a class called Customer that is marked as sealed. No other class can inherit from Customer class. For example, the below code generates a compile time error "MainClass cannot derive from sealed type Customer. using System; public sealed class Customer { } public class MainClass : Customer { public static void Main() { } } What are abstract methods? Abstract methods are methods that only the declaration of the method and no implementation. Will the following code compile? using System; public abstract class Customer { public abstract void Test() { Console.WriteLine("I am customer"); } } public class MainClass { public st...