2. An object is an instance of a class. 3. A class is the definition of an object. It does not actually become an object until it is instantiated. Since an abstract class can't be instantiated, no object of that type can created. A sub class would need to be defined in order for an object to created. 4. Yes, every instance of a class is an object. 5. Classes (whether abstract or not) are not objects. They are types.
A class is like a recipe. An object is a cake. From one recipe you can build many cakes. A recipe can only contain hints (be abstract) and leave room for your own creation of a recipe (implementing class) from which you can then build cakes (objects). So a class is not an object, it's the description of what objects of that class look like. Abstract classes contain methods and other information useful for the implementation of classes deriving from this abstract class. Objects cannot be created/instantiated from an abstract class (because it's definition is not complete). An abstract class can never be instantiated (and so can never become an object). If you create class that inherits from an abstract base class, and instantiate it, it will have properties of the abstract class as well as its own properties. The objective behind creating an abstract base class is to "enforce" deriving classes to implement certain functionality (similar to an interface, but not quite).
Yes. That's the definition of "instance. Abstract classes cannot be instantiated, hence they are not objects? Classes are not the same as instances or objects. An object is an instance of a class. Imagine a zoo simulation. An object is like a specific lion, whereas a class is more like a description of what a lion is. Abstract classes are descriptions of things that are too vague to make it reasonable to build something based on that description alone (e.g. "Animal"). That's why you can't instantiate them. Something like an Animal might be too vague for the program to request directly; instead, the program will only request more specific things like Lion, Tiger, or Mongoose. Basic Good 2) What is Polymorphism? The word polymorphism means having many forms. In object-oriented programming paradigm, polymorphism is often expressed as 'one interface, multiple functions'. Basic Not Good
Polymorphism can be static or dynamic. In static polymorphism the response to a function is determined at the compile time. In dynamic polymorphism , it is decided at run-time. Static Polymorphism The mechanism of linking a function with an object during compile time is called early binding. It is also called static binding. C# provides two techniques to implement t static polymorphism. These are: Function overloading Operator overloading We will discuss function overloading in the next section and operator overloading will be dealt with in next chapter. Function Overloading You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that differ only by return type. Following is the example where same function print() is being used to print different data types: using System; namespace PolymorphismApplication { class Printdata { void print(int i) { Console.WriteLine("Printing int: {0}", i ); }
void print(string s) { Console.WriteLine("Printing string: {0}", s); } static void Main(string[] args) { Printdata p = new Printdata(); // Call print to print integer p.print(5); // Call print to print float p.print(500.263); // Call print to print string p.print("Hello C++"); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result: Printing int: 5 Printing float: 500.263 Printing string: Hello C++ Dynamic Polymorphism C# allows you to create abstract classes that are used to provide partial class implementation of an interface. Implementation is completed when a derived class inherits from it. Abstract classes contain abstract methods, which are implemented by the derived class. The derived classes have more specialized functionality. Please note the following rules about abstract classes: You cannot create an instance of an abstract class You cannot declare an abstract method outside an abstract class When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed. The following program demonstrates an abstract class: using System; namespace PolymorphismApplication { abstract class Shape { public abstract int area(); } class Rectangle: Shape { private int length; private int width; public Rectangle( int a=0, int b=0) { length = a; width = b; } public override int area () { Console.WriteLine("Rectangle class area :"); return (width * length); } }
class RectangleTester { static void Main(string[] args) { Rectangle r = new Rectangle(10, 7); double a = r.area(); Console.WriteLine("Area: {0}",a); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result: Rectangle class area : Area: 70 When you have a function defined in a class that you want to be implemented in an inherited class(es), you use virtual functions. The virtual functions could be implemented differently in different inherited class and the call to these functions will be decided at runtime. Dynamic polymorphism is implemented by abstract classes and virtual functions. The following program demonstrates this: using System; namespace PolymorphismApplication { class Shape { protected int width, height; public Shape( int a=0, int b=0) { width = a; height = b; } public virtual int area() { Console.WriteLine("Parent class area :"); return 0; } } class Rectangle: Shape { public Rectangle( int a=0, int b=0): base(a, b) {
} public override int area () { Console.WriteLine("Rectangle class area :"); return (width * height); } } class Triangle: Shape { public Triangle(int a = 0, int b = 0): base(a, b) {
} public override int area() { Console.WriteLine("Triangle class area :"); return (width * height / 2); } } class Caller { public void CallArea(Shape sh) { int a; a = sh.area(); Console.WriteLine("Area: {0}", a); } } class Tester {
static void Main(string[] args) { Caller c = new Caller(); Rectangle r = new Rectangle(10, 7); Triangle t = new Triangle(10, 5); c.CallArea(r); c.CallArea(t); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result: Rectangle class area: Area: 70 Triangle class area: Area: 25
3) What is the difference between overloading and overriding? Overloading is defining functions that have similar signatures, yet have different parameters.
Basic Not Good
Overriding is only pertinent to derived classes, where the parent class has defined a method and the derived class wishes to override that function.
Overriding Overloading Methods name and signatures must be same. Having same method name with different Signatures. Overriding is the concept of runtime polymorphism Overloading is the concept of compile time polymorphism When a function of base class is re- defined in the derived class called as Overriding Two functions having same name and return type, but with different type and/or number of arguments is called as Overloading It needs inheritance. It doesn't need inheritance. Method should have same data type. Method can have different data types Method should be public. Method can be different access specifies
Example
Overriding
public class MyBaseClass { public virtual void MyMethod() { Console.Write("My BaseClass Method");
} } public class MyDerivedClass : MyBaseClass { public override void MyMethod() { Console.Write("My DerivedClass Method");
} }
Overloading
int add(int a, int b) int add(float a , float b)
4) Describe various access modifiers? Public, Private, Protected, Internal, Protected Internal Public The 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. Basic Ok
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. Static The static modifier on a class means that the class cannot be instantiated, and that all of its members are static. A static member has one version regardless of how many instances of its enclosing type are created. A static class is basically the same as a non-static class, but there is one difference: a static class cannot be externally instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself. However, there is a such thing as a static constructor. Any class can have one of these, including static classes. They cannot be called directly & cannot have parameters (other than any type parameters on the class itself). A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced. Looks like this: static class Foo() { static Foo() { Bar = "fubar"; }
public static string Bar { get; set; } } Static classes are often used as services, you can use them like so: MyStaticClass.ServiceMethod(...);
5) What is the significance of a static modifier? What are static methods and static
Good
members? Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object. The static modifier can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes. For more information, see Static Classes and Static Class Members (C# Programming Guide). Example
The following class is declared as static and contains only static methods: C# static class CompanyEmployee { public static void DoSomething() { /*...*/ } public static void DoSomethingElse() { /*...*/ } } A constant or type declaration is implicitly a static member. A static member cannot be referenced through an instance. Instead, it is referenced through the type name. For example, consider the following class: C# public class MyBaseC { public struct MyStruct { public static int x = 100; } } To refer to the static member x, use the fully qualified name, MyBaseC.MyStruct.x, unless the member is accessible from the same scope: C# Console.WriteLine(MyBaseC.MyStruct.x); While an instance of a class contains a separate copy of all instance fields of the class, there is only one copy of each static field. It is not possible to use this to reference static methods or property accessors. If the static keyword is applied to a class, all the members of the class must be static. Classes and static classes may have static constructors. Static constructors are called at some point between when the program starts and the class is instantiated. Note The static keyword has more limited uses than in C++. To compare with the C++ keyword, see Static (C++). To demonstrate static members, consider a class that represents a company employee. Assume that the class contains a method to count employees and a field to store the number of employees. Both the method and the field do not belong to any instance employee. Instead they belong to the company class. Therefore, they should be declared as static members of the class. This example reads the name and ID of a new employee, increments the employee counter by one, and displays the information for the new employee and the new number of employees. For simplicity, this program reads the current number of employees from the keyboard. In a real application, this information should be read from a file. C# public class Employee4 { public string id; public string name;
public static int AddEmployee() { return ++employeeCounter; } }
class MainClass : Employee4 { static void Main() { Console.Write("Enter the employee's name: "); string name = Console.ReadLine(); Console.Write("Enter the employee's ID: "); string id = Console.ReadLine();
// Create and configure the employee object: Employee4 e = new Employee4(name, id); Console.Write("Enter the current number of employees: "); string n = Console.ReadLine(); Employee4.employeeCounter = Int32.Parse(n); Employee4.AddEmployee();
// Display the new information: Console.WriteLine("Name: {0}", e.name); Console.WriteLine("ID: {0}", e.id); Console.WriteLine("New Number of Employees: {0}", Employee4.employeeCounter); } } /* Input: Matthias Berndt AF643G 15 * Sample Output: Enter the employee's name: Matthias Berndt Enter the employee's ID: AF643G Enter the current number of employees: 15 Name: Matthias Berndt ID: AF643G New Number of Employees: 16 */ This example shows that although you can initialize a static field by using another static field not yet declared, the results will be undefined until you explicitly assign a value to the static field. C# class Test { static int x = y; static int y = 5;
6) Difference between interface and abstract class 379 down vote accepted Interfaces An interface is a contract: the guy writing the interface say "hey, I accept things looking that way", and the guy using the interface says "OK, the class I write looks that way". An interface is an empty shell, there are only the signatures (name / params / return type) of the methods. The methods do not contain anything. The interface can't do anything. It's just a pattern. E.G (pseudo code): // I say all motor vehicles should look like that : interface MotorVehicle { void run();
int getFuel(); }
// my team mate complies and write vehicle looking that way class Car implements MotorVehicle {
int fuel;
void run() { print("Wrroooooooom"); }
int getFuel() { return this.fuel; } } Implementing an interface consume very little CPU, because it's not a class, just a bunch of names, and therefor there is no expensive lookup to do. It's great when it matters such as in embedded devices. Abstract classes Abstract classes, unlike interfaces, are classes. There are more expensive to use because there is a lookup to do when you inherit from them. Basic Not Good
Abstract classes look a lot like interfaces, but they have something more : you can define a behavior for them. It's more about a guy saying "these classes should look like that, and they got that in common, so fill in the blanks!". e.g: // I say all motor vehicles should look like that : abstract class MotorVehicle {
int fuel;
// they ALL have fuel, so why let others implement that ? // let's make it for everybody int getFuel() { return this.fuel; }
// that can be very different, force them to provide their // implementation abstract void run();
}
// my team mate complies and write vehicle looking that way class Car extends MotorVehicle { void run() { print("Wrroooooooom"); } } Implementation While abstract classes and interfaces are supposed to be different concepts, the implementations make that statement sometimes untrue. Sometimes, they are not even what you think they are. In Java, this rule is strongly enforced, while in PHP, interfaces are abstract classes with no method declared. In Python, abstract classes are more a programming trick you can get from the ABC module and is actually using metaclasses, and therefore classes. And interfaces are more related to duck typing in this language and it's a mix between conventions and special methods that call descriptors (the __method__ methods). Webservices What are WebServices? Web services enable applications to communicate in a loosely coupled environment by using predefined message exchanges built around standard protocols such as HTTP, XML, XSD, SOAP, and WSDL. Because the protocols and specifications are public and not platform- specific, Web services can be used to enable applications to communicate whether they reside on the same computer or not, even if they reside on different computing platforms or devices. Basic Not Good Talk to me about Restful vs. Soap web services Another doc Intermediate Not Good C# What are delegates? How are they Significant? Basic Not Good
A delegate is a type that safely encapsulates a method, similar to a function pointer in C and C++. Unlike C function pointers, delegates are object-oriented, type safe, and secure. The type of a delegate is defined by the name of the delegate. The following example declares a delegate named Del that can encapsulate a method that takes a string as an argument and returns void: C# public delegate void Del(string message); A delegate object is normally constructed by providing the name of the method the delegate will wrap, or with an anonymous Method. Once a delegate is instantiated, a method call made to the delegate will be passed by the delegate to that method. The parameters passed to the delegate by the caller are passed to the method, and the return value, if any, from the method is returned to the caller by the delegate. This is known as invoking the delegate. An instantiated delegate can be invoked as if it were the wrapped method itself. For example: C# // Create a method for a delegate. public static void DelegateMethod(string message) { System.Console.WriteLine(message); } C# // Instantiate the delegate. Del handler = DelegateMethod; Basic Not Good
// Call the delegate. handler("Hello World"); Delegate types are derived from the Delegate class in the .NET Framework. Delegate types are sealedthey cannot be derived from and it is not possible to derive custom classes from Delegate. Because the instantiated delegate is an object, it can be passed as a parameter, or assigned to a property. This allows a method to accept a delegate as a parameter, and call the delegate at some later time. This is known as an asynchronous callback, and is a common method of notifying a caller when a long process has completed. When a delegate is used in this fashion, the code using the delegate does not need any knowledge of the implementation of the method being used. The functionality is similar to the encapsulation interfaces provide. For more information, see When to Use Delegates Instead of Interfaces. Another common use of callbacks is defining a custom comparison method and passing that delegate to a sort method. It allows the caller's code to become part of the sort algorithm. The following example method uses the Del type as a parameter: C# public void MethodWithCallback(int param1, int param2, Del callback) { callback("The number is: " + (param1 + param2).ToString()); } You can then pass the delegate created above to that method: C# MethodWithCallback(1, 2, handler); and receive the following output to the console: The number is: 3 Using the delegate as an abstraction, MethodWithCallback does not need to call the console directlyit does not have to be designed with a console in mind. What MethodWithCallback does is simply prepare a string and pass the string to another method. This is especially powerful since a delegated method can use any number of parameters. When a delegate is constructed to wrap an instance method, the delegate references both the instance and the method. A delegate has no knowledge of the instance type aside from the method it wraps, so a delegate can refer to any type of object as long as there is a method on that object that matches the delegate signature. When a delegate is constructed to wrap a static method, it only references the method. Consider the following declarations: C# public class MethodClass { public void Method1(string message) { } public void Method2(string message) { } } Along with the static DelegateMethod shown previously, we now have three methods that can be wrapped by a Del instance. A delegate can call more than one method when invoked. This is referred to as multicasting. To add an extra method to the delegate's list of methodsthe invocation listsimply requires adding two delegates using the addition or addition assignment operators ('+' or '+='). For example: C# MethodClass obj = new MethodClass(); Del d1 = obj.Method1; Del d2 = obj.Method2; Del d3 = DelegateMethod;
//Both types of assignment are valid. Del allMethodsDelegate = d1 + d2; allMethodsDelegate += d3; At this point allMethodsDelegate contains three methods in its invocation list Method1, Method2, and DelegateMethod. The original three delegates, d1, d2, and d3, remain unchanged. When allMethodsDelegate is invoked, all three methods are called in order. If the delegate uses reference parameters, the reference is passed sequentially to each of the three methods in turn, and any changes by one method are visible to the next method. When any of the methods throws an exception that is not caught within the method, that exception is passed to the caller of the delegate and no subsequent methods in the invocation list are called. If the delegate has a return value and/or out parameters, it returns the return value and parameters of the last method invoked. To remove a method from the invocation list, use the decrement or decrement assignment operator ('-' or '-='). For example: C# //remove Method1 allMethodsDelegate -= d1;
// copy AllMethodsDelegate while removing d2 Del oneMethodDelegate = allMethodsDelegate - d2; Because delegate types are derived from System.Delegate, the methods and properties defined by that class can be called on the delegate. For example, to find the number of methods in a delegate's invocation list, you may write: C# int invocationCount = d1.GetInvocationList().GetLength(0); Delegates with more than one method in their invocation list derive from MulticastDelegate, which is a subclass of System.Delegate. The above code works in either case because both classes support GetInvocationList. Multicast delegates are used extensively in event handling. Event source objects send event notifications to recipient objects that have registered to receive that event. To register for an event, the recipient creates a method designed to handle the event, then creates a delegate for that method and passes the delegate to the event source. The source calls the delegate when the event occurs. The delegate then calls the event handling method on the recipient, delivering the event data. The delegate type for a given event is defined by the event source. For more, see Events (C# Programming Guide). Comparing delegates of two different types assigned at compile-time will result in a compilation error. If the delegate instances are statically of the type System.Delegate, then the comparison is allowed, but will return false at run time. For example: C# delegate void Delegate1(); delegate void Delegate2();
// OK at compile-time. False if the run-time type of f // is not the same as that of d. System.Console.WriteLine(d == f); }
What are Namespaces? How are they significant? The namespace keyword is used to declare a scope. This namespace scope lets you organize code and gives you a way to create globally unique types. A namespace is designed for providing a way to keep one set of names separate from another. The class names declared in one namespace will not conflict with the same class names declared in another. Defining a Namespace A namespace definition begins with the keyword namespace followed by the namespace name as follows: namespace namespace_name { // code declarations } To call the namespace-enabled version of either function or variable, prepend the namespace name as follows: namespace_name.item_name; The following program demonstrates use of namespaces: using System; namespace first_space { class namespace_cl { public void func() { Console.WriteLine("Inside first_space"); } } } namespace second_space { class namespace_cl { public void func() { Console.WriteLine("Inside second_space"); } } } class TestClass { static void Main(string[] args) { first_space.namespace_cl fc = new first_space.namespace_cl(); second_space.namespace_cl sc = new second_space.namespace_cl(); fc.func(); sc.func(); Console.ReadKey(); } } When the above code is compiled and executed, it produces the following result: Inside first_space Inside second_space
C# namespace SampleNamespace { class SampleClass { }
interface SampleInterface { }
struct SampleStruct { }
enum SampleEnum { a, b }
delegate void SampleDelegate(int i);
namespace SampleNamespace.Nested { class SampleClass2 { } } } Remarks
Within a namespace, you can declare one or more of the following types: another namespace class interface struct enum delegate Whether or not you explicitly declare a namespace in a C# source file, the compiler adds a default namespace. This unnamed namespace, sometimes referred to as the global namespace, is present in every file. Any identifier in the global namespace is available for use in a named namespace. Namespaces implicitly have public access and this is not modifiable. For a discussion of the access modifiers you can assign to elements in a namespace, see Access Modifiers (C# Reference). It is possible to define a namespace in two or more declarations. For example, the following example defines two classes as part of the MyCompany namespace: C# namespace MyCompany.Proj1 { class MyClass { } }
namespace MyCompany.Proj1 { class MyClass1 { } } Example
The following example shows how to call a static method in a nested namespace. C# namespace SomeNameSpace { public class MyClass { static void Main() { Nested.NestedNameSpaceClass.SayHello(); } }
// a nested namespace namespace Nested { public class NestedNameSpaceClass { public static void SayHello() { Console.WriteLine("Hello"); } } } } // Output: Hello
Talk to me about Stringbuilder class. How is it different from String? Basic Not Good A string instance is immutable. You cannot change it after it was created. Any operation that appears to change the string instead returns a new instance: string foo = "Foo"; // returns a new string instance instead of changing the old one string bar = foo.Replace('o', 'a'); string baz = foo + "bar"; // ditto here Immutable objects have some nice properties, such as they can be used across threads without fearing synchronization problems or that you can simply hand out your private backing fields directly without fearing that someone changes objects they shouldn't be changing (see arrays or mutable lists, which often need to be copied before returning them if that's not desired). But when used carelessly they may create severe performance problems (as nearly anything if you need an example from a language that prides itself on speed of execution then look at C's string manipulation functions). Basic OK
When you need a mutable string, such as one you're contructing piece-wise or where you change lots of things, then you'll need a StringBuilder which is a buffer of characters that can be changed. This has, for the most part, performance implications. If you want a mutable string and instead do it with a normal string instance, then you'll end up with creating and destroying lots of objects unnecessarily, whereas a StringBuilder instance itself will change, negating the need for many new objects. Simple example: The following will make many programmers cringe with pain: string s = string.Empty; for (i = 0; i < 1000; i++) { s += i.ToString() + " "; } You'll end up creating 2001 strings here, 2000 of which are thrown away. The same example using StringBuilder: StringBuilder sb = new StringBuilder(); for (i = 0; i < 1000; i++) { sb.Append(i); sb.Append(' '); } This should place much less stress on the memory allocator :-) It should be noted however, that the C# compiler is reasonably smart when it comes to strings. For example, the following line string foo = "abc" + "def" + "efg" + "hij"; will be joined by the compiler, leaving only a single string at runtime. Similarly, lines such as string foo = a + b + c + d + e + f; will be rewritten to string foo = string.Concat(a, b, c, d, e, f); so you don't have to pay for five nonsensical concatenations which would be the nave way of handling that. This won't save you in loops as above (unless the compiler unrolls the loop but I think only the JIT may actually do so and better don't bet on that).
Difference between foreach and for loops FOR Collapse | Copy Code int[] myInterger = new int[1]; int total = 0; for(int i = 0; i < myInterger.Length; i++) { total += myInterger[i]; } foreach Collapse | Copy Code int[] myInterger = new int[1]; int total = 0; foreach(int i in myInterger) { total += i; } Both codes will produce the same result. foreach is used on top of collections to traverse through while for can be used on anything for the same purpose. Im not going to explain whatsoever about the code. Before going in more deeper, I think all of you are familiar with ILDasm which is used to generate IL code, and CorDbg tool which is normally used to generate JIT compiled code. The IL code produced by C# compiler is optimized up to certain extend, while leaving some part to JIT. Anyway, this is not really what matters to us. So, when we talk about the optimization, two things we must consider. First is C# compiler and the second is JIT. So, rather than looking more deep into IL code, we will see more about the code which is emitted by JIT. That is the code which will run on our machine. Im now using AMD Athlon 1900+. The code highly depends on our hardware. Therefore, what you may get from your machine may differ from mine up to a certain extend. Anyway, the algorithms wont change that much. In variable declaration, foreach has five variable declarations (three Int32 integers and two arrays of Int32) while for has only three (two Int32 integers and one Int32 array). When it goes to loop through, foreach copies the current array to a new one for the operation. While for doesn't care of that part. Here, Im going into the exact difference between the codes. FOR Collapse | Copy Code Instruction Effect Collapse | Copy Code cmp dword ptr [eax+4],0 i<myInterger.Length jle 0000000F mov ecx,dword ptr [eax+edx*4+8] total += myInterger[i] inc edx ++i cmp esi,dword ptr [eax+4] i<myInterger.Length jl FFFFFFF8 Ill explain what is happening here. The esi register which holds the value of i and the length of myInteger array are compared at two stages. The first one is done only once to check the condition and if the loop can continue, the value is added. For the loop, it is done at the second stage. Inside the loop, it is well optimized and as explained, the work is done with perfect optimization. foreach Collapse | Copy Code Instruction Effect Collapse | Copy Code cmp esi,dword ptr [ebx+4] i<myInterger.Length jl FFFFFFE3 cmp esi,dword ptr [ebx+4] i<myInterger.Length jb 00000009 mov eax,dword ptr [ebx+esi*4+8] mov dword ptr [ebp-0Ch],eax mov eax,dword ptr [ebp-0Ch] add dword ptr [ebp-8],eax total += i inc esi ++i cmp esi,dword ptr [ebx+4] i<myInterger.Length jl FFFFFFE3 Anyone will say that both are not the same. But we will look why it differs from the for loop. The main reason for the difference is that both of them are differently understood by the compiler. The algorithm they are using is different. Two compare statements one after the other is unnecessary. It is doing the same thing again and again for no reason! Collapse | Copy Code cmp esi,dword ptr [ebx+4] jl FFFFFFE3 cmp esi,dword ptr [ebx+4] It also uses some unnecessary move statements which also may (not always, but depends) reduce the performance of the code. foreach is thinking everything as a collection and treating them as a collection. I feel, that will also reduce the performance of the work. Therefore, I strongly feel if you are planning to write high performance code that is not for collections, use for loop. Even for collections, foreach may look handy when using, but it's not that efficient. Therefore, I strongly recommend everyone to use for loop rather than foreach at any stage.
Talk about exception handling in C# n exception is a problem that arises during the execution of a program. A C# exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. Exceptions provide a way to transfer control from one part of a program to another. C# exception handling is built upon four keywords: try, catch, finally and throw. try: A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks. catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception. finally: The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not. throw: A program throws an exception when a problem shows up. This is done using a throw keyword. Syntax Assuming a block will raise and exception, a method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following: try { // statements causing exception } catch( ExceptionName e1 ) { // error handling code } catch( ExceptionName e2 ) { // error handling code } catch( ExceptionName eN ) { // error handling code } finally { // statements to be executed } Basic Ok
You can list down multiple catch statements to catch different type of exceptions in case your try block raises more than one exception in different situations. Exception Classes in C# C# exceptions are represented by classes. The exception classes in C# are mainly directly or indirectly derived from the System.Exception class. Some of the exception classes derived from the System.Exception class are the System.ApplicationException and System.SystemException classes. The System.ApplicationException class supports exceptions generated by application programs. So the exceptions defined by the programmers should derive from this class. The System.SystemException class is the base class for all predefined system exception.
Talk about logging and best practices in logging within your application http://www.gibraltarsoftware.com/Support/Documentation/logging_bestpractices.html Basic Not Good How do you create web services using Visual C#? http://msdn.microsoft.com/en-us/library/8wbhsy70%28v=vs.90%29.aspx Intermediate Not Good What is an Assembly? What is a Dll? Assemblies form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions for a .NET-based application. Assemblies take the form of an executable (.exe) file or dynamic link library (.dll) file, and are the building blocks of the .NET Framework. They provide the common language runtime with the information it needs to be aware of type implementations. You can think of an assembly as a collection of types and resources that form a logical unit of functionality and are built to work together. Assemblies can contain one or more modules. For example, larger projects may be planned in such a way that several individual developers work on separate modules, all coming together to create a single assembly. For more information about modules, see the topic How to: Build a Multifile Assembly. Assemblies have the following properties:
Basic Not Good
Assemblies are implemented as .exe or .dll files. You can share an assembly between applications by putting it in the global assembly cache. Assemblies must be strong-named before they can be included in the global assembly cache. For more information, see Strong- Named Assemblies. Assemblies are only loaded into memory if they are required. If they are not used, they are not loaded. This means that assemblies can be an efficient way to manage resources in larger projects. You can programmatically obtain information about an assembly by using reflection. For more information, see Reflection. If you want to load an assembly only to inspect it, use a method such as ReflectionOnlyLoadFrom.
In most scenarios, an assembly contains all or part of a reusable library and is contained in a single dynamic-link library (DLL). An assembly can be split among multiple DLLs but this is very uncommon Where assemblies and DLLs are the physical organization of a library, namespaces are a logical organization and should be factored independent of the assembly's organization. Namespaces can and often do span multiple assemblies.
What are the different ways of reading a file in C#? Which is the most efficient way? Intermediate Not Good
TextReader and TextWriter are base classes (abstract ones, I believe) used by many other classes for handling different kinds of I/O. StreamReader and StreamWriter should be used when you're actually dealing with Stream objects containing text, such as the FileStream for a text file. But a TextReader need not necessarily deal with streams; take the StringReader class, for example, which also inherits from TextReader and just reads a simple string.
File.ReadLines (.NET 4.0+) is probably the most memory efficient way to do this. It returns an IEnumerable<string> meaning that lines will get read lazily in a streaming fashion. Previous versions do not have the streaming option available in this manner, but using StreamReader to read line by line would achieve the same. //Declare a new file and give it the path to your file FileInfo fi1 = new FileInfo(path);
//Open the file and read the text using (StreamReader sr = fi1.OpenText()) { string s = ""; Intermediate Not Good Knows about Python // Loop through each line while ((s = sr.ReadLine()) != null) { //Here is where you handle your row in the file Console.WriteLine(s);
What is serialization? How can we serialize an object in C#? Serialization is the process of converting an object into a stream of bytes in order to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization. To serialize an object, you need the object to be serialized, a stream to contain the serialized object, and a Formatter. System.Runtime.Serialization contains the classes necessary for serializing and deserializing objects. Apply the SerializableAttribute attribute to a type to indicate that instances of this type can be serialized. A SerializationException exception is thrown if you attempt to serialize but the type does not have the SerializableAttribute attribute. If you do not want a field within your class to be serializable, apply the NonSerializedAttribute attribute. If a field of a serializable type contains a pointer, a handle, or some other data structure that is specific to a particular environment, and the field cannot be meaningfully reconstituted in a different environment, then you may want to make it nonserializable. If a serialized class contains references to objects of other classes that are marked SerializableAttribute, those objects will also be serialized.
What are the different ways of creating multithreaded programs in C#? Explicit use of Thread class, Threadpool, Task Parallel Library, Action class with lambda functions, BeginInvoke, BackgroundWorker Advanced Not Good Theoretical Knowledge
http://www.tutorialspoint.com/csharp/csharp_multithreading.htm Thread class are called the child threads of the main thread. You can access a thread using the CurrentThread property of the Thread class. The following program demonstrates main thread execution: using System; using System.Threading; Advanced Not Good
namespace MultithreadingApplication { class MainThreadProgram { static void Main(string[] args) { Thread th = Thread.CurrentThread; th.Name = "MainThread"; Console.WriteLine("This is {0}", th.Name); Console.ReadKey(); } } } Thread pooling is a form of multithreading in which tasks are added to a queue and automatically started when threads are created. For more information, see Thread Pooling (C# and Visual Basic). The following example uses the .NET Framework thread pool to calculate the Fibonacci result for ten numbers between 20 and 40. Each Fibonacci result is represented by the Fibonacci class, which provides a method named ThreadPoolCallback that performs the calculation. An object that represents each Fibonacci value is created, and the ThreadPoolCallback method is passed to QueueUserWorkItem, which assigns an available thread in the pool to execute the method. Because each Fibonacci object is given a semi-random value to compute, and because each thread will be competing for processor time, you cannot know in advance how long it will take for all ten results to be calculated. That is why each Fibonacci object is passed an instance of the ManualResetEvent class during construction. Each object signals the provided event object when its calculation is complete, which allows the primary thread to block execution with WaitAll until all ten Fibonacci objects have calculated a result. The Main method then displays each Fibonacci result. http://msdn.microsoft.com/en-us/library/3dasc8as.aspx
Background worker class. What is it? http://www.dotnetperls.com/backgroundworker BackgroundWorker makes threads easy to implement in Windows Forms. Intensive tasks need to be done on another thread so the UI does not freeze. It is necessary to post messages and update the user interface when the task is done. Steps In the image, you see the Visual Studio designer view. The fly-out panel is the Toolboxit contains links for all kinds of controls. It also contains the BackgroundWorker link, which we can use in the following steps.
First, click on BackgroundWorker. You will need to double-click on BackgroundWorker link in the Toolbox. Look at the gray bar near the bottom of your window. A BackgroundWorker will appear there. Second: Highlight backgroundWorker1. Click on the backgroundWorker1 item in the gray bar on the bottom. Now, look at the Properties panel. Third: Look for the lightning bolt. You will see a lightning bolt icon in the Properties pane. This is Microsoft's icon for events. Tip: BackgroundWorker is event-driven, so this is where we will make the necessary events to use it. Then, double-click on DoWork. Sorry, but we have to begin working. Double-click on DoWork, which will tell Visual Studio to make a new "work" method. In this method, you will put the important, processor-intensive stuff.
The rectangles show the tray at the bottom containing the backgroundWorker1 icon, and the Properties panel on the right. The lightning bolt helps us easily add events to the BackgroundWorker. Tip: This UI is far better than trying to type the methods in manually. It requires less effort on your part. Add DoWork
The DoWork method is like any other event handler. Here we must look at the C# view of your file, where we will see the DoWork method. You should see that the backgroundWorker1_DoWork event is generated when you double-click on DoWork. For testing, let's add a Thread.Sleep command there. The Thread.Sleep method will pause the execution of the BackgroundWorker, but does not consume the entire CPU. It will show us threading is functioning. Sleep
Databases: Primary Key, Foreign key, Unique Key What are they? 9 down vote accepted Primary Key and Unique Key are Entity integrity constraints Primary key allows each row in a table to be uniquely identified and ensures that no duplicate rows exist and no null values are entered. Unique key constraint is used to prevent the duplication of key values within the rows of a table and allow null values. (In oracle one null is not equal to another null). KEY or INDEX refers to a normal non-unique index. Non- distinct values for the index are allowed, so the index may contain rows with identical values in all columns of the index. These indexes don't enforce any structure on your data so they are used only for speeding up queries. UNIQUE refers to an index where all rows of the index must be unique. That is, the same row may not have identical non-NULL values for all columns in this index as another row. As well as being used to speed up queries, UNIQUE indexes can be used to Basic Good
enforce structure on data, because the database system does not allow this distinct values rule to be broken when inserting or updating data. Your database system may allow a UNIQUE index on columns which allow NULL values, in which case two rows are allowed to be identical if they both contain a NULL value (NULL is considered not equal to itself), though this is probably undesirable depending on your application. PRIMARY acts exactly like a UNIQUE index, except that it is always named 'PRIMARY', and there may be only one on a table (and there should always be one; though some database systems don't enforce this). A PRIMARY index is intended as a way to uniquely identify any row in the table, so it shouldn't be used on any columns which allow NULL values. Your PRIMARY index should always be on the smallest number of columns that are sufficient to uniquely identify a row. Often, this is just one column containing a unique auto-incremented number, but if there is anything else that can uniquely identify a row, such as "countrycode" in a list of countries, you can use that instead. FULLTEXT indexes are different to all of the above, and their behaviour differs more between database systems. Unlike the above three, which are typically b-tree (allowing for selecting, sorting or ranges starting from left most column) or hash (allowing for selection starting from left most column), FULLTEXT indexes are only useful for full text searches done with the MATCH() / AGAINST() clause. see Differences between INDEX, PRIMARY, UNIQUE, FULLTEXT in MySQL? What are the different types of Joins? Basic Ok 1. Inner join or Equi join 2. Outer Join 3. Cross join Inner Join This type of join is also known as the Equi join. This join returns all the rows from both tables where there is a match. This type of join can be used in the situation where we need to select only those rows which have values common in the columns which are specified in the ON clause. SELECT Emp.Empid, Emp.EmpFirstName, Emp.EmpLastName, Dept.DepartmentName FROM Employee Emp INNER JOIN Department dept ON Emp.Departmentid=Dept.Departmenttid Self Join Intermediate
Sometime we need to join a table to itself. This type of join is called Self join. It is one of the type of inner join where both the columns belong to the same table. In this Join, we need to open two copies of a same table in the memory. Since the table name is the same for both instances, we use the table aliases to make identical copies of the same table to be open in different memory locations. For example if we need to get the employee name and their manager name we need to use the self join, since the managerid for an employee is also stored in the same table as the employee. Query for the Self Join Collapse | Copy Code SELECT Emp1.Empid, Emp1.EmpFirstName+' '+Emp1.EmpLastName as EmployeeName, Emp2.EmpFirstName+' '+Emp2.EmpLastName as ManagerName FROM Employee Emp1 INNER JOIN Employee Emp2 ON Emp1.Managerid=Emp2.Empid Result Collapse | Copy Code Empid EmployeeName ManagerName 1 Samir Singh Amit Kumar 2 Amit Kumar Samir Singh 3 Neha Sharma Samir Singh 4 Vivek Kumar Samir Singh Outer Join This type of join is needed when we need to select all the rows from the table on the left (or right or both) regardless of whether the other table has common values or not and it usually enter null values for the data which is missing. The Outer join can be of three types 1. Left Outer Join 2. Right Outer Join 3. Full Outer Join Left Outer Join If we want to get employee id, employee first name, employes last name and their department name for all the employees regardless of whether they belong to any department or not,then we can use the left outer join. In this case we keep the Employee table on the left side of the join clause. It will insert NULL values for the data which is missing in the right table. Query for Left Outer Join Collapse | Copy Code SELECT Emp.Empid, Emp.EmpFirstName, Emp.EmpLastName, Dept.DepartmentName FROM Employee Emp LEFT OUTER JOIN Department dept ON Emp.Departmentid=Dept.Departmenttid Result Collapse | Copy Code Empid EmpFirstName EmpLastName DepartmentName 1 Samir Singh Admin 2 Amit Kumar Accounts 3 Neha Sharma Admin 4 Vivek Kumar NULL Explanation Since we have use the Left Outer Join, this query will give the information (Employee id, Employee first name, Employee last name and their department name) for all the employee from the Employee table and it insert NULL value in the DepartmentName column where the employee does not belong to any department. In the table Employee, since Samir Singh, Amit Kumar and Neha Sharma have values in their Departmentid column, therefore the above query will display their Department name under the heading DepartmentName.But since Vivek Kumar doesn't belongs to any department and has null value in the column Departmentid therefore the above query will Display the NULL value under the column heading DepartmentName. Right Outer Join If we want to get all the departments name and employee id, employee first name, and employees last name of all the employees belonging to the department regardless of whether a department have employees or not, then we can use the right outer join. In this case we keep the Department table on the right side of the join clause. It will insert NULL values for the data which is missing in the left table (Employee). Query for Right Outer Join Collapse | Copy Code SELECT Dept.DepartmentName, Emp.Empid, Emp.EmpFirstName, Emp.EmpLastName FROM Employee Emp RIGHT OUTER JOIN Department dept ON Emp.Departmentid=Dept.Departmentid Result Collapse | Copy Code DepartmentName Empid EmpFirstName EmpLastName Accounts 2 Amit Kumar Admin 1 Samir Singh Admin 3 Neha Sharma HR NULL NULL NULL Technology NULL NULL NULL Explanation Since we have use the Right Outer Join, this query will join the two tables Employee and Department on the basis of the values contains in the column Departmenttid. It will give the department name from the Department table and the Employee id, Employee first name, and Employee last name of all the employees that belong to that department. If any department does not contain any employee then it insert NULL value in the columns coming from the Employee table. Since no employee is connected to the departments HR and Technology, this query will display NULL values under the columns Empid, EmpFirstName and EmpLastName for the Departments HR and Technology. Since the department Admin and Accounts contains the employees therefore the columns Empid, EmpFirstName and EmpLastName contains the information, employee id, employee first name and employee last name respectively. Full Outer Join If we want to get all the departments name and the employee id, employee first name, employes last name of all the employees regardless of whether a department have employees or not, or whether a employee belong to a department or not, then we can use the full outer join. It will insert null values for the data which is missing in both the tables. Query for Full Outer Join Collapse | Copy Code SELECT Emp.Empid, Emp.EmpFirstName, Emp.EmpLastName, Dept.DepartmentName FROM Employee Emp FULL OUTER JOIN Department dept ON Emp.Departmentid=Dept.Departmenttid Result Collapse | Copy Code Empid EmpFirstName EmpFirstName DepartmentName 1 Samir Singh Admin 2 Amit Kumar Accounts 3 Neha Sharma Admin 4 Vivek Kumar NULL NULL NULL NULL HR NULL NULL NULL Technology Explanation Since we have used the Full Outer Join, this query will give the name of all the departments from the Department table and the Employee id, Employee first name, Employee last name of all the employees from the Employee table. If any department does not contain any employee, then it insert NULL value in the columns Empid, EmpFirstName, EmpLastName columns and if any employee doesn't belong to any department then it insert NULL value in the column DepartmentName. Here since Vivek Kumar doesn't belong to any department, the result displays NULL value under the column DepartmentName. Since the departments HR and Accounts don't contain any employees, the result of the above query displays NULL values under the columns Empid, EmpFirstName and EmpLastName for the departments HR and Technology.. Cross Join This join combines all the rows from the left table with every row from the right table. This type of join is needed when we need to select all the possible combinations of rows and columns from both the tables. This type of join is generally not preferred as it takes lot of time and gives a huge result that is not often useful. Query for the Cross Join Collapse | Copy Code SELECT Emp.Empid, Emp.EmpFirstName, Emp.EmpLastName, Dept.DepartmentName FROM Employee Emp CROSS JOIN Department dept Results Collapse | Copy Code Empid EmpFirstName EmpLastName DepartmentName 1 Samir Singh Accounts 2 Amit Kumar Accounts 3 Neha Sharma Accounts 4 Vivek Kumar Accounts 1 Samir Singh Admin 2 Amit Kumar Admin 3 Neha Sharma Admin 4 Vivek Kumar Admin 1 Samir Singh HR 2 Amit Kumar HR 3 Neha Sharma HR 4 Vivek Kumar HR 1 Samir Singh Technology 2 Amit Kumar Technology 3 Neha Sharma Technology 4 Vivek Kumar Technology
How do you identify duplicate records in a database table?
You probably want this SELECT dewey_number, author_last_name, COUNT(dewey_number) AS NumOccurrences FROM book GROUP BY dewey_number,author_last_name HAVING ( COUNT(dewey_number) > 1 ) It's easy to find duplicates with one field SELECT name, COUNT(email) FROM users GROUP BY email HAVING ( COUNT(email) > 1 )
What is the difference between a view and a table? Basic Ok
A table contains data, a view is just a SELECT statement which has been saved in the database (more or less, depending on your database). The advantage of a view is that it can join data from several tables thus creating a new view of it. Say you have a database with salaries and you need to do some complex statistical queries on it. Instead of sending the complex query to the database all the time, you can save the query as a view and then SELECT * FROM view
Misc: What is the difference between Checkin, checkout and update operations on a source code repository? http://en.wikipedia.org/wiki/Revision_control Basic Ok Trading: What is a Futures trade? http://en.wikipedia.org/wiki/Futures_trading Basic Not Good General Questions -What are some of the programming best practises you followed in your past experience?
Not very clear
http://msdn.microsoft.com/en-us/library/aa260844%28v=vs.60%29.aspx select a,com, a.emp, e.sal from (select SELECT AVG(salary) FROM able d Group by comp WHERE d.emp_id = e.emp_id ) b, table a