1 Explain General Structure of Csharp Program.?
1 Explain General Structure of Csharp Program.?
Solutions Set
C# and DotNet
Namespace declaration
A class
Class methods
Class attributes
A Main method
Statements and Expressions
Comments
Let us look at a simple code that prints the words "Hello World" −
Live Demo
using System;
namespace HelloWorldApplication {
class HelloWorld {
static void Main(string[] args) {
/* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}
When this code is compiled and executed, it produces the following result −
Hello World
Let us look at the various parts of the given program −
The first line of the program using System; - the using keyword is used to include the System
namespace in the program. A program generally has multiple using statements.
The next line has the namespace declaration. A namespace is a collection of classes. The
HelloWorldApplication namespace contains the class HelloWorld.
The next line has a class declaration, the class HelloWorld contains the data and method
definitions that your program uses. Classes generally contain multiple methods. Methods define
the behavior of the class. However, the HelloWorld class has only one method Main.
The next line defines the Main method, which is the entry point for all C# programs. The Main
method states what the class does when executed.
The next line /*...*/ is ignored by the compiler and it is put to add comments in the program.
The Main method specifies its behavior with the statement Console.WriteLine("Hello World");
WriteLine is a method of the Console class defined in the System namespace. This statement
causes the message "Hello, World!" to be displayed on the screen.
The last line Console.ReadKey(); is for the VS.NET Users. This makes the program wait for a
key press and it prevents the screen from running and closing quickly when the program is
launched from Visual Studio .NET.
Array type:
A C# program consists of the following parts −
Namespace declaration
A class
Class methods
Class attributes
A Main method
Statements and Expressions
Comments
Let us look at a simple code that prints the words "Hello World" −
Live Demo
using System;
namespace HelloWorldApplication {
class HelloWorld {
static void Main(string[] args) {
/* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}
When this code is compiled and executed, it produces the following result −
Hello World
Let us look at the various parts of the given program −
The first line of the program using System; - the using keyword is used to include the System
namespace in the program. A program generally has multiple using statements.
The next line has the namespace declaration. A namespace is a collection of classes. The
HelloWorldApplication namespace contains the class HelloWorld.
The next line has a class declaration, the class HelloWorld contains the data and method
definitions that your program uses. Classes generally contain multiple methods. Methods define
the behavior of the class. However, the HelloWorld class has only one method Main.
The next line defines the Main method, which is the entry point for all C# programs. The Main
method states what the class does when executed.
The next line /*...*/ is ignored by the compiler and it is put to add comments in the program.
The Main method specifies its behavior with the statement Console.WriteLine("Hello World");
WriteLine is a method of the Console class defined in the System namespace. This statement
causes the message "Hello, World!" to be displayed on the screen.
The last line Console.ReadKey(); is for the VS.NET Users. This makes the program wait for a
key press and it prevents the screen from running and closing quickly when the program is
launched from Visual Studio .NET.
Delegate type:
XX obj = new XX();
obj.MyEvent += new MyDelegate(obj.Add);
obj.MyEvent += new MyDelegate(obj.Subtract);
obj.RaiseEvent(20, 10);
Console.ReadLine();
}
}
}
filter_none
edit
play_arrow
brightness_4
// C# Program to illustrate the use
// of Default Constructor
using System;
namespace GFG {
class multiplication
{
int a, b;
// default Constructor
public multiplication()
{
a = 10;
b = 5;
}
// Main Method
public static void Main() {
// an object is created,
// constructor is called
multiplication obj = new multiplication();
Console.WriteLine(obj.a);
Console.WriteLine(obj.b);
}
}
Output:
10
5
The result of multiplication is: 50
Example 2: In this example, the class Person does not have any constructors, in which case, a
default constructor is automatically provided and the fields are initialized to their default values.
filter_none
edit
play_arrow
brightness_4
// C# Program to illustrate the use
// of Default Constructor
using System;
// Driver Class
class TestPerson {
// Main Method
static void Main() {
// object creation
Person pers = new Person();
}
}
Output:
Name: , Age: 0
Note: The output is so because a string is assigned to null by default and integers to 0.
In c#, Logical Operators are used to perform the logical operation between two operands like
AND, OR and NOT based on our requirements. The Logical Operators will always work with
Boolean expressions (true or false) and return Boolean values.
The operands in logical operators must always contain only Boolean values otherwise Logical
Operators will throw an error.
Following table lists the different type of operators available in c# relational operators.
In case if we use Logical NOT operator in our c# applications, it will return the results like as
shown below for different inputs.
Operand NOT
true false
false true
If you observe above table, the Logical NOT operator will always return the reverse value of
operand like if operand value true, then the Logical NOT operator will return false and vice
versa.
using System;
namespace Tutlane
class Program
// AND operator
// OR operator
//NOT operator
result = !a;
Console.ReadLine();
}
If you observe above code, we used a logical operators (AND, OR, NOT) to perform different
operations on defined operands.
Following table shows all the relational operators supported by C#. Assume variable A holds 10
and variable B holds 20, then −
Example
The following example demonstrates all the relational operators available in C# −
Live Demo
using System;
class Program {
static void Main(string[] args) {
int a = 21;
int b = 10;
if (a == b) {
Console.WriteLine("Line 1 - a is equal to b");
} else {
Console.WriteLine("Line 1 - a is not equal to b");
}
if (a < b) {
Console.WriteLine("Line 2 - a is less than b");
} else {
Console.WriteLine("Line 2 - a is not less than b");
}
if (a > b) {
Console.WriteLine("Line 3 - a is greater than b");
} else {
Console.WriteLine("Line 3 - a is not greater than b");
}
if (a <= b) {
Console.WriteLine("Line 4 - a is either less than or equal to b");
}
if (b >= a) {
Console.WriteLine("Line 5-b is either greater than or equal to b");
}
}
}
When the above code is compiled and executed, it produces the following result −
5 What is creation of object in csharp? Explain accessing class members with example?
Object:
Object, in C#, is an instance of a class that is created dynamically. Object is also a keyword that
is an alias for the predefined type System.Object in the .NET framework.
The unified type system of C# allows objects to be defined. These can be user-defined, reference
or value type, but they all inherit directly or indirectly from System.Object. This inheritance is
implicit so that the type of the object need not be declared with System.Object as the base class.
In general, object type is useful where there is a requirement to build generic routines. Because
values of any type can be assigned to variables of object type, object type is used mostly in
designing classes that handle objects of any type that allow code to be reused. The non-generic
collection classes in the .NET framework library, such as ArrayList, Queue, etc., use object type
to define various collections.
An object is also known as instance.
We can access a private variable in a different class by putting that variable with in a Public
method and calling that method from another class by creating object of that class.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class PrivateVariable
{
private int i = 10; //Declaring and initializing a private variable
public void DisplayVariable()
{
Console.Write("The Value of Private Variable=" + i); //Accessing Private variable with
in a public methode
}
}
class DisplayPrivateVariable
{
static void Main()
{
PrivateVariable objPrivateVariable = new PrivateVariable();
objPrivateVariable.DisplayVariable(); //Calling the public method
}
}
}
By Using Inner class
By using inner class also we can access a private variable of a class in another class. For better
understanding have look at the example.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class PrivateVariable2
{
class Outerclass
{
private int i = 10;
private int j = 20;
class Innerclass
{
static void Main()
{
Outerclass objouter = new Outerclass();
int Result = objouter.i + objouter.j;
Console.Write("Sum=" + Result);
Console.ReadLine();
}
}
}
}
}
By Using Properties
Overloaded methods are differentiated based on the number and type of the parameters passed as
arguments to the methods.
You can not define more than one method with the same name, Order and the type of the
arguments. It would be compiler error.
The compiler does not consider the return type while differentiating the overloaded method. But
you cannot declare two methods with the same signature and different return type. It will throw a
compile-time error. If both methods have the same parameter types, but different return type,
then it is not possible.
Why do we need Method Overloading ??
If we need to do the same kind of the operation in different ways i.e. for different inputs. In the
example described below, we are doing the addition operation for different inputs. It is hard to
find many different meaningful names for single action.
filter_none
edit
play_arrow
brightness_4
// C# program to demonstrate the function
// overloading by changing the Number
// of parameters
using System;
class GFG {
// Main Method
public static void Main(String[] args)
{
// Creating Object
GFG ob = new GFG();
filter_none
edit
play_arrow
brightness_4
// C# program to demonstrate the function
// overloading by changing the Data types
// of the parameters
using System;
class GFG {
// Main Method
public static void Main(String[] args)
{
// Creating Object
GFG ob = new GFG();
filter_none
edit
play_arrow
brightness_4
// C# program to demonstrate the function
// overloading by changing the
// Order of the parameters
using System;
class GFG {
// Method
public void Identity(String name, int id)
{
// Method
public void Identity(int id, String name)
{
// Main Method
public static void Main(String[] args)
{
// Creating Object
GFG obj = new GFG();
obj.Identity("Akku", 1);
obj.Identity("Abby", 2);
}
}
Output:
Name : Akku, Id : 1
Name : Abby, Id : 2
What happens when method signature is same and the return type is different?
The compiler will give error as the return value alone is not sufficient for the compiler to figure
out which function it has to call. Only if both methods have different parameter types (so, they
have the different signature), then Method overloading is possible.
Example:
filter_none
edit
play_arrow
brightness_4
// C# program to show error when method signature
// is the same and the return type is different.
using System;
class GFG {
// adding two integer value.
public int Add(int a, int b)
{
int sum = a + b;
return sum;
}
// Main Method
public static void Main(String[] args)
{
// Creating Object
GFG ob = new GFG();
prog.cs(15,19): error CS0111: A member `GFG.Add(int, int)’ is already defined. Rename this
member or use different parameter types
prog.cs(7,16): (Location of the symbol related to previous error)
In the Multilevel inheritance, a derived class will inherit a base class and as well as the derived
class also act as the base class to other class. For example, three classes called A, B, and C, as
shown in the below image, where class C is derived from class B and class B, is derived from
class A. In this situation, each derived class inherit all the characteristics of its base classes. So
class C inherits all the features of class A and B.
Example: Here, the derived class Rectangle is used as a base class to create the derived class
called ColorRectangle. Due to inheritance the ColorRectangle inherit all the characteristics of
Rectangle and Shape and add an extra field called rcolor, which contains the color of the
rectangle.
This example also covers the concept of constructors in a derived class. As we know that a
subclass inherits all the members (fields, methods) from its superclass but constructors are not
members, so they are not inherited by subclasses, but the constructor of the superclass can be
invoked from the subclass. As shown in the below example, base refers to a constructor in the
closest base class. The base in ColorRectangle calls the constructor in Rectangle and the base in
Rectangle class the constructor in Shape.
filter_none
edit
play_arrow
brightness_4
// C# program to illustrate the
// concept of multilevel inheritance
using System;
class Shape {
double a_width;
double a_length;
// Default constructor
public Shape()
{
Width = Length = 0.0;
}
set {
a_width = value < 0 ? -value : value;
}
}
set {
a_length = value < 0 ? -value : value;
}
}
public void DisplayDim()
{
Console.WriteLine("Width and Length are "
+ Width + " and " + Length);
}
}
string Style;
// A default constructor.
// This invokes the default
// constructor of Shape.
public Rectangle()
{
Style = "null";
}
// Constructor
public Rectangle(string s, double w, double l)
: base(w, l)
{
Style = s;
}
// Construct an square.
public Rectangle(double y)
: base(y)
{
Style = "square";
}
string rcolor;
// Constructor
public ColorRectangle(string c, string s,
double w, double l)
: base(s, w, l)
{
rcolor = c;
}
// Main Method
static void Main()
{
ColorRectangle r1 = new ColorRectangle("pink",
"Fibonacci rectangle", 2.0, 3.236);
Sealed classes are used to restrict the users from inheriting the class. A class can be sealed by
using the sealed keyword. The keyword tells the compiler that the class is sealed, and therefore,
cannot be extended. No class can be derived from a sealed class.
}
A method can also be sealed, and in that case, the method cannot be overridden. However, a
method can be sealed in the classes in which they have been inherited. If you want to declare a
method as sealed, then it has to be declared as virtual in its base class.
In the following code, create a sealed class SealedClass and use it from Program. If you run this
code then it will work fine.
filter_none
edit
play_arrow
brightness_4
// C# code to define
// a Sealed Class
using System;
// Sealed class
sealed class SealedClass {
// Calling Function
public int Add(int a, int b)
{
return a + b;
}
}
class Program {
// Main Method
static void Main(string[] args)
{
Total = 10
Now, if it is tried to inherit a class from a sealed class then an error will be produced stating that
” It cannot be derived from a Sealed class.
filter_none
edit
play_arrow
brightness_4
// C# code to show restrictions
// of a Sealed Class
using System;
class Bird {
// Driver Class
class Program {
// Main Method
static void Main()
{
}
}
Error:
filter_none
edit
play_arrow
brightness_4
// C# program to
// define Sealed Class
using System;
class Printer {
// Display Function
public virtual void print()
{
Console.WriteLine("printer printing....\n");
}
}
// inherting class
class LaserJet : Printer {
// Function to override
// Print() function
override public void print()
{
Console.WriteLine("Laserjet printer printing....\n");
}
}
// Driver Class
class Program {
// Driver Code
static void Main(string[] args)
{
Printer p = new Printer();
p.show();
p.print();
Sealed class is used to stop a class to be inherited. You cannot derive or extend any class from it.
Sealed method is implemented so that no other class can overthrow it and implement its own
method.
The main purpose of the sealed class is to withdraw the inheritance attribute from the user so that
they can’t attain a class from a sealed class. Sealed classes are used best when you have a class
with static members.
e.g the “Pens” and “Brushes” classes of the System.Drawing namespace. The Pens class
represents the pens for standard colors. This class has only static members. For example,
“Pens.Red” represents a pen with red color. Similarly, the “Brushes” class represents standard
brushes. “Brushes.Red” represents a brush with red color.
Garbage Collector:
The garbage collector (GC) manages the allocation and release of memory. The garbage
collector serves as an automatic memory manager.
You do not need to know how to allocate and release memory or manage the lifetime of the
objects that use that memory.
An allocation is made any time you declare an object with a “new” keyword or a value type is
boxed. Allocations are typically very fast.
When there isn’t enough memory to allocate an object, the GC must collect and dispose of
garbage memory to make memory available for new allocations.
You don’t need to free memory manually while developing your application.
When objects are no longer used then it will reclaim those objects by clearing their memory, and
keeps the memory available for future allocations.
Managed objects automatically get clean content to start with, so their constructors do not have
to initialize every data field.
C# enumerations are value data type. In other words, enumeration contains its own values and
cannot inherit or cannot pass inheritance.
enum <enum_name> {
enumeration list
};
Where,
Each of the symbols in the enumeration list stands for an integer value, one greater than the
symbol that precedes it. By default, the value of the first enumeration symbol is 0. For example −
Live Demo
using System;
namespace EnumApplication {
class EnumProgram {
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
Monday: 1
Friday: 5
10. Write a program to search an element in the array?
using System;
using System.IO;
class Program
{
static void Main()
{
Like string in c#, we can use a StringBuilder to create a variables to hold any kind of text which
is a sequential collection of characters based on our requirements.
In c#, both string and StringBuilder will represent a sequence of characters and perform a same
kind of operations but only difference is strings are immutable and StringBuilder is mutable.
Generally, in c# the string object cannot be modified once it created. If any changes made to the
string object like add or modify an existing value, then it will simply discard the old instance in
memory and create a new instance to hold the new value. In case, if we are doing a repeated
modifications on the string object, then it will effect the performance of application. To know
more about strings, check this strings in c# with examples.
In c#, the StringBuilder declaration and initialization will be same like class. Following are the
different ways of declaring and initializing a stringbuilder in c# programming language.
//or
If you observe above code snippet, we created an instance of StringBuilder class by defining our
variable with overloaded constructor methods.
C# StringBuilder Capacity
As discussed, the StringBuilder is a dynamic object which will expands dynamically to
accommodate the number of characters based on the string modifications. We can also specify an
initial capacity of characters, the StringBuilder can hold by passing an int value using one of the
overloaded constructors or by using StringBuilder Capacity property.
For example, we created a StringBuilder by specifying a capacity of 25 characters and appending
a string whose length is greater than the capacity of 25 characters. In this case, the new space
will be allocated automatically and the capacity of StringBuilder will be doubled.
Following is the example of specifying the initial capacity of characters the StringBuilder can
hold in c# programming language.
//or
//or
sb.Capacity = 25;
In c#, whenever the defined capacity of StringBuilder is lesser than the appended string value,
then the current capacity of StringBuilder automatically will increase to match the appended
string value.
The default capacity of StringBuilder is 16 characters and its maximum capacity is more than 12
billion characters.
C# StringBuilder Methods
Following table lists the important methods of StringBuilder which we can use to modify the
contents of StringBuilder.
Method Description
StringBuilder.Append This method will append the given string value to the end of current
StringBuilder.
StringBuilder.AppendFormat It will replaces a format specifier passed in a string with formatted
text.
StringBuilder.Insert It inserts a string at the specified index of current StringBuilder.
StringBuilder.Remove It removes a specified number of characters from the current
StringBuilder.
StringBuilder.Replace It replaces a specified character at a specified index.
C# StringBuilder Append Method
The Append method is used to add or append a string objects to the end of string represented by
the StringBuilder.
Following is the example of initializing a StringBuilder with some text and appending a required
text to the end of string object.
sb.Append(", Rohini");
sb.Append(", Trishika");
Console.WriteLine(sb);
Following is the example of initializing a StringBuilder with some text and appending a
formatted text to the end of string object.
Following is the example of initializing a StringBuilder with some text and inserting a string at
the specified index position of StringBuilder object.
Console.WriteLine(sb);
Following is the example of removing a specified number of characters from the StringBuilder
object, starting from the specified index position.
sb.Remove(8, 3);
Console.WriteLine(sb);
sb.Replace("Tutlane","C#");
Console.WriteLine(sb);
// Output: Welcome to C#
In c#, the StringBuilder is having another method called AppendLine() which is used to add a
newline to the end of string.
C# StringBuilder Example
Following is the example of using StringBuilder to insert or append or replace or to remove a
particular string text in c# programming language.
using System;
using System.Text;
namespace Tutlane
class Program
sb.Append(", Rohini");
sb.Append(", Trishika");
sb.AppendLine();
sb.Append("Welcome to Tutlane");
Console.WriteLine(sb);
sb2.Remove(8, 3);
Console.WriteLine(sb2);
sb3.Replace("Tutlane", "C#");
Console.WriteLine(sb3);
Console.ReadLine();
If you observe above code, to use StringBuilder in our application we imported a System.Text
namespace and used a different methods of StringBuilder to make required modifications based
on our requirements.
When we execute above c# program, we will get the result like as shown below.
This is how we can use StringBuilder in our applications to make required modifications to the
string objects based on our requirements.
Following is the example of converting a StringBuilder object to string using ToString() method
in c# programming language.
using System;
using System.Text;
namespace Tutlane
class Program
sb.Append(", Rohini");
sb.Append(", Trishika");
sb.AppendLine();
sb.Append("Welcome to Tutlane");
Console.WriteLine(sb.ToString());
Console.ReadLine();
If you observe above code, we are converting StringBuilder object (sb) to string object using
sb.ToString() method.
When we execute above c# program, we will get the result like as shown below.
This is how we can convert StringBuilder object to string based on our requirements.
In c#, the StringBuilder will offer a better performance than string but we should not
automatically replaces a string with StringBuilder whenever we want to manipulate a strings.
Use StringBuilder in C#
Following are the important points which we needs to remember while using a StringBuilder in
c# programming language.
We need to consider using StringBuilder only when we are unknown about the number of
changes which will make to a string at design time otherwise StringBuilder will offer a
negligible or no performance improvement over string.
When we are performing a fixed number of concatenation operations on string, then it’s better to
avoid using StringBuilder because it will offer negligible performance.
In another case when we expect our application will make a significant number of changes to a
string, then we need to use StringBuilder instead of string.
try
{
do{
i=fin.ReadByte();
if(i!= -1) fout.WriteByte((byte)i);
}while(i!=-1);
}catch{Console.WriteLine("error");}
Console.WriteLine("reading is over");
Console.ReadLine();
The .NET Framework is a new and revolutionary platform created by Microsoft for developing
applications
You can use a utility of a language in another language (It uses Class Language Integration).
.NET Framework includes no restriction on the type of applications that are possible. The .NET
Framework allows the creation of Windows applications, Web applications, Web services, and
lot more.
The .NET Framework has been designed so that it can be used from any language, including C#,
C++, Visual Basic, JScript, and even older languages such as COBOL.
Web Application
All websites are example of web application. They use a web server.
Peer to Peer
Web Services
It doesn't use web-based server. Internet payment systems are example of web services.
DLL Hell
"DLL Hell" refers to the set of problems caused when multiple applications attempt to share a
common component like a dynamic link library (DLL) or a Component Object Model (COM)
class.
The reason for this issue was that the version information about the different components of an
application was not recorded by the system. (Windows Registry cannot support the multiple
versions of same COM component this is called the dll hell problem.)
.Net Framework provides operating systems with a Global Assembly Cache (GAC). This Cache
is a repository for all the .Net components that are shared globally on a particular machine. When
a .Net component is installed onto the machine, the Global Assembly Cache looks at its version,
its public key, and its language information and creates a strong name for the component. The
component is then registered in the repository and indexed by its strong name, so there is no
confusion between different versions of the same component, or DLL.
It is a subset of CTS. All instruction is in CLS i.e. instruction of CTS is written in CLS.
Code Manager
1. Managed Code
2. Unmanaged Code
14. What are the benefits of multiple language integration? Explain?
The most ambitious aspect of the CLR is that it is designed to support multiple languages and
allow unprecedented levels of integration among those languages. By enforcing a common type
system, and by having complete control over interface calls, the CLR allows languages to work
together more transparently than ever before.
Previously, one language could instantiate and use components written in another language by
using COM. Sometimes calling conventions were difficult to manage, especially when Visual
Basic was involved, but it could generally be made to work. However, subclassing a component
written in a different language required a sophisticated wrapper, and only advanced developers
did such work.
It is straightforward in the .NET Framework to use one language to subclass a class implemented
in another language. A class written in Visual Basic can inherit from a base class written in C++,
or in COBOL for that matter (at least one major vendor is at work on a COBOL implementation
for .NET). The VB program doesn't even need to know the language used for the base class, and
we're talking full implementation inheritance with no problems requiring recompilation when the
base
class changes.
How can this work? The information furnished by metadata makes it possible. There is no
Interface Definition Language (IDL) in .NET because none is needed. A class interface looks the
same, regardless of the language that generated it. The CLR uses metadata to manage all the
interfaces and calling conventions between languages.
This has major implications; mixed language programming teams become far more feasible than
before. And it becomes less necessary to force developers who are perfectly comfortable in one
language to adopt another just to fit into a development effort. Cross-language inheritance
promises to open up architectural options than never existed before.
One Microsoft person summed this up by saying that, as far as they are concerned, with .NET,
the language used becomes a "lifestyle choice". While there will always be benefits to
programming teams using a common language, .NET raises the practicality of mixed-language
projects.
A key piece of functionality that enables Multiple Language Support is a Common Type System,
in which all commonly used data types, even base types such as Longs and Booleans, are
actually implemented as objects. Coercion among types can now be done at a lower level for
more consistency between languages. And, since all languages are using the same library of
types, calling one language from another doesn't require type conversion or weird calling
conventions.
This results in the need for some readjustment, particularly for Visual Basic developers. For
example, what we called an Integer in VB6 and earlier, is now known as a Short in Visual
Basic.NET. The adjustment is well worth the effort in order to bring VB in line with everything
else - and, as a by-product, other languages get the same support for strings that VB has always
had.
This a basic question which allways asked in the interview that what is the namespace ,do you
know about namespace,can you tell me some words about namespace.
NameSpace is the Logical group of types or we can say namespace is a container (e.g Class,
Structures, Interfaces, Enumerations, Delegates etc.), example System.IO logically groups
input output related features , System.Data.SqlClient is the logical group of ado.net Connectivity
with Sql server related features. In Object Oriented world, many times it is possible that
programmers will use the same class name, Qualifying NameSpace with class name can avoid
this collision.
Example :-
// Namespace Declaration
using System;
// The Namespace
namespace MyNameSpace
{
// Program start class
class MyClass
{
//Functionality
Namespaces allow you to create a system to organize your code. A good way to organize your
namespaces is via a hierarchical system. You put the more general names at the top of the
hierarchy and get more specific as you go down. This hierarchical system can be represented by
nested namespaces. Bellow shows how to create a nested namespace. By placing code in
different sub-namespaces, you can keep your code organized.
User Interface
Window Forms
Windows forms (also called Win Forms) ate used to create GUI-for Windows desktop
applications. The idea of Win Form has been borrowed from Windows Foundation Classes
(WFC) which was used for Visual J++. Win Form provide an integrated and unified way of
developing -GUI. It has a rich variety of windows controls and user interface support.
Numerous classes and functions were used by programmers to handle GUT. MFC in VC++,
direct API in C++ and VB Forms Engine in VB are just a few examples of different ways of
handling GUI.
Simply Win Form is just another group of wrapper classes that deal specifically with GUI. Win
Form classes encapsulate the Windows Graphical APIs. Now the programmers would not need
to use the Windows Graphical APIs directly; and since Win Form has been made apart of .NET.
Class Framework; all the programming languages would use the same Win Form classes. This
would rid the programmers of the need to learn different· GUI classes/tools. Win Forms in the
part of the namespace System Winforms.
With Win Forms we can make a single user interface, and use it in VC++, VB, C#. Using
Visual Studio. NET simply designs the GUI, by dragging the controls on a form (something that
all VC++ and VB programmers are well familiar with). Now you can use the same form either in
VB, VC++ or in C#. And this is all made possible because Visual Studio.NET uses the System.
Winforms namespace to draw the GUI. And any language that has the appropriate CLS
compliance can use this form directly.
Web Forms
Just as the Win Forms provide a unified way of developing GUI for desktop application, the
Web Forms provide similar tool for web applications. Web Forms has been introduced in .NET
as a part of ASP.NET. Web' Forms are a form engine, that provides a browser-based user
interface.
To appreciate Web Forms you may consider how GUI is rendered in current Web applications.
The GUI is rendered by using HTML tags. (e.g. <input type=text name=editboxl maxlength=10
size=10 >, will draw an edit box on the web page) Web Forms can also have the intelligence to
use HTML, DHTML, and WML etc. to draw the controls on the web page based on the
browser's capabilities. Web Forms can also incorporate the logic behind these controls. It’s like
hooking up the code to a GUI control. Just like in your VB application, you can associate a code
with a button on the web page; this code will be run on the server when the button is pressed.
This is in contrast to the scripts that run on the clients when a button is pressed.
This approach is different to the Java approach. In Java a programmer can simulate this
functionality through JavaScript and Servlets. But with Web forms this is done transparently.
A Java programmer may consider as if each HTML control has its dedicated "Servlets" running
in the background. Every time the control receives any event of interest (e.g. button pressed,
selection changed etc.) this specific "Servlets" is called. This results in much cleaner code and an
excellent logic separation between presentation and business logic layers.
Web Forms consist of two parts - a template, which contains HTML-based
layout information for all the GUI elements and a Component which contains all the logic to be
hooked to the controls or GUI elements. This provides a neat presentation layer and application
logic layer separation.
The GUI will be rendered on the client side, while the code that has been hooked to the GUI
elements will run on the server side (very 'much likes a button being pressed on a JSP and a
Servlets being called in response. But with Win Forms this has been made extremely easy). The
incorporation of Web Forms in ASP.NET is an attempt to take ASP to a new level where it can
seriously challenge JSP.
Another good feature of Web Forms is that it can be built to have enough intelligence to support
a vast variety of browsers. The same ASP page would render itself using DHTML, if the browser
is IE 5.5. But if the browser is Netscape the web page will be rendered using HTML tags; if the'
page is being accessed through a WAP device the same page will render itself using WML tags.
One of the obvious disadvantages of ASP over Java was that there was that an ASP code was a
maintenance nightmare. While a Java programmer can use Java Beans, Tags and also Servlets to
achieve presentation and business layer separation - no such mechanism was present to an ASP
programmer. With ASP.NET Microsoft 'has provided such presentation business, layer
separation - by introducing the concept of Web Forms:
1. ASP.NET Web Forms provide an easy and to build dynamic Web UI.
2. ASP.NET Web Forms pages can target any browser client (there are no script library or.
cookie requirements).
3. ASP.NET Web Forms pages· provide syntax compatibility with existing ASP pages.
4. ASP.NET server controls provide an easy way to encapsulate common functionality.
5. ASP.NET ships with 45 built-in server controls. Developers can also use controls built by
third parties.
6. ASP.NET templates provide an easy way to customize the look and feel of list server controls.
7. ASP.NET validation controls provide an easy way to do declarative client ·or server data
validation.
Console Application
Console applications are command line oriented applications that allow user to read characters
from the· console, write characters to the console.
Console applications are typically designed without graphical user interface and are compiled in
a stand-alone executable file.
A console application is run from the command line with input and output information being
exchanged between the command prompt and the running application. Because information can
be written to and read from .the console window, this makes the console application a great way
to learn new programming techniques without having to be concerned with the user interface.
Web Services
A web service is an extension of ActiveX. Those programmers, who have used ASP and JSP
both, know the apparent shortcomings of ASP. JSP has been enriched with the concepts of
Beans. And Tags. ASP equivalent for Beans and Tags was ActiveX Controls. and ActiveX
automation servers. Let me take a minute to explain this point a bit further. Web Services is NOT
a Microsoft proprietary standard. It is a W3Consortium standard, and has been developed by
Microsoft, IBM and many other big names of the industry.
Functions are of two types. The ASP built-in functions and the programmer defined implemented
functions. In order to use the built in functions you just need to pass the appropriate parameters
and make a simple call to these functions. The functions are implemented by the ASP itself. The
string manipulation functions, Number conversion functions are an, example of built in
functions.
The user-defined functions are the functions that are defined and implemented by the
programmer. A programmer can either write these functions in the same asp file or can write
them in another file. If the function code resides in the same asp file then the programmer can
directly call that function. In case the function resides in another file, say "func.asp"; then the
programmer needs to include that file by writing a statement like <!- #include file="func.asp" ->;
and now the programmer can use the function. The programmers can also make ActiveX
automation servers, and call various functions of these ActiveX servers, But one limitation is
very obvious - no matter which type of function you use, the function MUST physically reside on
the same machine. For example your ActiveX automation server must be implemented either as
a .dll or as an .exe and then must also be registered in Windows Registry before an asp code can
call its functions.
In a world where the Intemet has become not only a necessity but also a way of life – it is
obvious that this limitation is a strong one; Microsoft's answer to this problem is "Web Services".
The idea goes something like this:
1. The Web service provider develops a useful function(s), and publish/advertise it. The
Web Service provider uses Web Service Description Language (WSDL) standard to describe the
interface of the function(s). This is much like the Type Libraries (TLB) and Object Description
Language files (ODL) that needs to be generated with the ActiveX automation servers.
2. The programmer/client who needs the function does a lookup by using a process called
- Web Service Discovery or SOAP Discovery (also called DISCO for Web Service DISCOvery)
3. The Actual communication between the client program and the web service takes place
through a protocol called Simple Object Access Protocol (SOAP) -SOAP is an XML based light
weight protocol used for communication in a decentralized distributed environment.
16. What are web services? Explain the web services provided in C#?
A Web Service is a software program that uses XML to exchange information with other
software via common internet protocols. In a simple sense, Web Services are a way of
interacting with objects over the Internet.
A web service is
Language Independent.
Protocol Independent.
Platform Independent.
It assumes a stateless service architecture.
Scalable (e.g. multiplying two numbers together to an entire customer-relationship
management system).
Programmable (encapsulates a task).
Based on XML (open, text-based standard).
Self-describing (metadata for access and use).
Discoverable (search and locate in registries)- ability of applications and developers to
search for and locate desired Web services through registries. This is based on UDDI.
Microsoft coined the term "Web services" in June 2000, when the company introduced
Web services as a key component of its .Net initiative, a broad new vision for embracing
the Internet in the development, engineering and use of software.
As others began to investigate Web services, it became clear that the technology could
revolutionize (be the next stage in) distributed computing.
Web services encom a set of related standards that can enable any two computers to
communicate and exchange data via a network, such as the Internet.
The primary standard used in Web services is the Extensible Markup Language (XML)
developed by the World Wide Web Consortium (W3C).
Developers use XML tags to describe individual pieces of data, forming XML
documents, which are text-based and can be processed on any platform.
XML provides the foundation for many core Web services standards (SOAP, WSDL, and
UDDI) and vocabularies (XML-based markup for a specific industry or purpose).
Almost every type of business can benefit from Web services such as expediting software
development, integrating applications and databases, and automating transactions with
suppliers, partners, and clients.
XML- Describes only data. So, any application that understands XML-regardless of the
application's programming language or platform has the ability to format XML in a
variety of ways (well-formed or valid).
SOAP- Provides a communication mechanism between services and applications.
WSDL- Offers a uniform method of describing web services to other programs.
UDDI- Enables the creation of searchable Web services registries.
When these technologies are deployed together, they allow developers to package applications as
services and publish those services on a network.
Use open, text-based standards, which enable components written in various languages
and for different platforms to communicate.
Promote a modular approach to programming, so multiple organizations can
communicate with the same Web service.
Comparatively easy and inexpensive to implement, because they employ an existing
infrastructure and because most applications can be repackaged as Web services.
Significantly reduce the costs of enterprise application (EAI) integration and B2B
communications.
Implemented incrementally, rather than all at once which lessens the cost and reduces the
organizational disruption from an abrupt switch in technologies.
The Web Services Interoperability Organization (WS-I) consisting of over 100 vendors
promotes interoperability.
Web Portal- A web portal might obtain top news headlines from an Associated press web
service.
Weather Reporting- You can use Weather Reporting web service to display weather
information in your personal website.
Stock Quote- You can display latest update of Share market with Stock Quote on your
web site.
News Headline: You can display latest news update by using News Headline Web
Service in your website.
You can make your own web service and let others use it. For example you can make
Free SMS Sending Service with footer with your companies advertisement, so whosoever
uses this service indirectly advertises your company. You can apply your ideas in N no.
of ways to take advantage of it.
CLR provides multiple services to execute processes, like memory management service and
security services. CLR performs multiple tasks to manage the execution of .NET
applications. Following responsibilities of CLR are given below:
1. Automatic memory management
2. Code access security
3. Garbage collection
4. JIT compilation
1) Automatic memory management CLR calls various predefined functions of .NET framework
to allocate and de-allocate memory of .NET objects. So that, developers need not to write code to
explicitly allocate and de-allocate memory.
2) Code access security
CLR allows access to code to perform only those tasks for that it has permission. It also checks
user’s permissions using authentication and configuration files of .NET applications.
3) Garbage collection
GC is used to prevent memory leaks or holes. Garbage collector of CLR automatically
determines the best time to free the memory, which is allocated to an object for execution.
4) JIT compilation
JIT stands for Just In Time. It is also an important part of Common Language Runtime (CLR),
JIT compiler converts MSIL code to targeted machine code for execution.
18. Explain with example how boxing and unboxing acts as a bridge between value type and
reference type?
Boxing and unboxing enable a unified view of the type system wherein a value of any type can
ultimately be treated as an object. Converting a value type into reference type is called Boxing.
Unboxing is an explicit operation.
C# provides a "unified type system". All types including value types derive from the type object.
It is possible to call the object methods on any value, even values of "primitive" types, such as
int. The example is shown below.
using System;
class Test
{
static void Main()
{
Console.WriteLine(3.ToString());
}
}
It calls the object-defined ToString method on an integer literal. The example -
class Test
{
static void Main()
{
int i = 1;
object o = i; // boxing
int j = (int)o; // unboxing
}
}
An int value can be converted into object and back again into int.
This example shows both, boxing and unboxing. When a variable of a value type needs to be
converted into a reference type, an object box is allocated to hold the value, and the value is
copied into the box.
Unboxing is just the opposite. When an object box is cast back to its original value type, the
value is copied out of the box and into the appropriate storage location.
Boxing conversions
A boxing conversion permits any value-type to be implicitly converted to the type object or to
any interface-type implemented by the value-type. Boxing a value of a value-type consists of
allocating an object instance and copying the value-type value into that instance.
For example, for any value-type G, the boxing class would be declared as follows:
class vBox
{
Gvalue;
G_Box(G g)
{
value = g;
}
}
Boxing of a value v of type G now consists of executing the expression new G_Box(v), and
returning the resulting instance as a value of type object. Thus, the statements
int i = 12;
object box = i;
conceptually correspond to,
int i = 12;
object box = new int_Box(i);
Boxing classes like G_Box and int_Box above don't actually exist and the dynamic type of a
boxed value isn't actually a class type. Instead, a boxed value of type G has the dynamic type G,
and a dynamic type check using the is operator can simply reference type G.
For example -
int i = 12;
object box = i;
if (box is int)
{
Console.Write("Box contains an int");
}
The above code will output the string "Box contains an int" on the console.
A boxing conversion implies making a copy of the value being boxed. This is different from a
conversion of a reference-type to type object, in which the value continues to reference the same
instance and simply is regarded as the less derived type object.
Unboxing conversions
An unboxing conversion permits an explicit conversion from type object to any value-type or
from any interface-type to any value-type that implements the interface-type. An unboxing
operation consists of first checking that the object instance is a boxed value of the given value-
type, and then copying the value out of the instance. Unboxing conversion of an object box to a
value-type G consists of executing the expression ((G_Box)box).value.
2. Shared Assemblies: Microsoft offers the shared assembly for those components that must
be distributed. It centered around two principles.
Firstly, called side-by-side execution, allows the CLR to house multiple
versions of the same component on a single machine.
Secondly, termed binding, ensures that clients obtain the version of the
component they expect.
20. What is Garbage Collection? Specify its importance? Write the ways to optimize garbage
collection?
In the common language runtime (CLR), the garbage collector serves as an automatic memory
manager. It provides the following benefits:
Enables you to develop your application without having to free memory.
Allocates objects on the managed heap efficiently.
Reclaims objects that are no longer being used, clears their memory, and keeps the memory
available for future allocations. Managed objects automatically get clean content to start with, so
their constructors do not have to initialize every data field.
Provides memory safety by making sure that an object cannot use the content of another object.
This topic describes the core concepts of garbage collection.
Fundamentals of memory
The following list summarizes important CLR memory concepts.
Each process has its own, separate virtual address space. All processes on the same computer
share the same physical memory, and share the page file if there is one.
By default, on 32-bit computers, each process has a 2-GB user-mode virtual address space.
As an application developer, you work only with virtual address space and never manipulate
physical memory directly. The garbage collector allocates and frees virtual memory for you on
the managed heap.
If you are writing native code, you use Win32 functions to work with the virtual address space.
These functions allocate and free virtual memory for you on native heaps.
Virtual memory can be in three states:
Free. The block of memory has no references to it and is available for allocation.
Reserved. The block of memory is available for your use and cannot be used for any other
allocation request. However, you cannot store data to this memory block until it is committed.
Committed. The block of memory is assigned to physical storage.
Virtual address space can get fragmented. This means that there are free blocks, also known as
holes, in the address space. When a virtual memory allocation is requested, the virtual memory
manager has to find a single free block that is large enough to satisfy that allocation request.
Even if you have 2 GB of free space, the allocation that requires 2 GB will be unsuccessful
unless all of that free space is in a single address block.
You can run out of memory if you run out of virtual address space to reserve or physical space to
commit.
While developing an application, a developer creates many objects that occupy memory. An
excess amount of unmanaged memory slows down the application performance. Traditional
programming languages do not provide garbage collection features such as C
language. Although C language ideally suits for embedded systems because of its low-level
control portability and structured programming. So, working with such kind of programming
languages end up with the much effort of freeing up memory manually. Dot net provides its
native garbage collection feature and developer no longer has to explicitly free memory. Dot net
garbage collector automatically releases the memory when a block of memory is no longer need
in the program. This technique prevents memory leaks. In this article, I will explain how to
collect garbage memory or objects in dot net c#. So let’s start.