Saturday, July 12, 2008

C#/VB.Net

VB.NET
Program Structure
C#


Imports System

Namespace Hello
Class HelloWorld
Overloads Shared Sub Main(ByVal args() As String)
Dim name As String = "VB.NET"

'See if an argument was passed from the command line
If args.Length = 1 Then name = args(0)

Console.WriteLine("Hello, " & name & "!")
End Sub
End Class
End Namespace using System;

namespace Hello {
public class HelloWorld {
public static void Main (string[] args) {
string name = "C#";

// See if an argument was passed from the command line
if (args.Length == 1)
name = args[0];

Console.WriteLine("Hello, " + name + "!");
}
}
}
VB.NET
Comments
C#


' Single line only
Rem Single line only // Single line
/* Multiple
line */
/// XML comments on single line
/** XML comments on multiple lines */
VB.NET
Data Types
C#


Value Types
Boolean
Byte
Char (example: "A"c)
Short, Integer, Long
Single, Double
Decimal
Date
Reference Types
Object
String
Dim x As Integer
Console.WriteLine(x.GetType()) ' Prints System.Int32
Console.WriteLine(TypeName(x)) ' Prints Integer
' Type conversion
Dim d As Single = 3.5
Dim i As Integer = CType(d, Integer) ' set to 4 (Banker's rounding)
i = CInt(d) ' same result as CType
i = Int(d) ' set to 3 (Int function truncates the decimal) Value Types
bool
byte, sbyte
char (example: 'A')
short, ushort, int, uint, long, ulong
float, double
decimal
DateTime (not a built-in C# type)
Reference Types
object
string
int x;
Console.WriteLine(x.GetType()); // Prints System.Int32
Console.WriteLine(typeof(int)); // Prints System.Int32

// Type conversion
float d = 3.5f;
int i = (int) d; // set to 3 (truncates decimal)
VB.NET
Constants
C#


Const MAX_STUDENTS As Integer = 25
' Can set to a const or var; may be initialized in a constructor
ReadOnly MIN_DIAMETER As Single = 4.93 const int MAX_STUDENTS = 25;
// Can set to a const or var; may be initialized in a constructor
readonly float MIN_DIAMETER = 4.93f;
VB.NET
Enumerations
C#


Enum Action
Start
[Stop] ' Stop is a reserved word
Rewind
Forward
End Enum

Enum Status
Flunk = 50
Pass = 70
Excel = 90
End Enum

Dim a As Action = Action.Stop
If a <> Action.Start Then _
Console.WriteLine(a.ToString & " is " & a) ' Prints "Stop is 1"

Console.WriteLine(Status.Pass) ' Prints 70
Console.WriteLine(Status.Pass.ToString()) ' Prints Pass enum Action {Start, Stop, Rewind, Forward};
enum Status {Flunk = 50, Pass = 70, Excel = 90};

Action a = Action.Stop;
if (a != Action.Start)
Console.WriteLine(a + " is " + (int) a); // Prints "Stop is 1"

Console.WriteLine((int) Status.Pass); // Prints 70
Console.WriteLine(Status.Pass); // Prints Pass
VB.NET
Operators
C#


Comparison
= < > <= >= <>
Arithmetic
+ - * /
Mod
\ (integer division)
^ (raise to a power)
Assignment
= += -= *= /= \= ^= <<= >>= &=
Bitwise
And AndAlso Or OrElse Not << >>
Logical
And AndAlso Or OrElse Not
Note: AndAlso and OrElse are for short-circuiting logical evaluations
String Concatenation
& Comparison
== < > <= >= !=
Arithmetic
+ - * /
% (mod)
/ (integer division if both operands are ints)
Math.Pow(x, y)
Assignment
= += -= *= /= %= &= |= ^= <<= >>= ++ --
Bitwise
& | ^ ~ << >>
Logical
&& || !
Note: && and || perform short-circuit logical evaluations
String Concatenation
+
VB.NET
Choices
C#


greeting = IIf(age < language = "VB.NET" langtype = "verbose"> 100 And y <> 100 And y <> Lines Then _
UseTheUnderscore(charToBreakItUp)
'If x > 5 Then
x *= y
ElseIf x = 5 Then
x += y
ElseIf x < greeting =" age"> 5)
x *= y;
else if (x == 5)
x += y;
else if (x < 10)
x -= y;
else
x /= y;


switch (color) { // Must be integer or string
case "pink":
case "red": r++; break; // break is mandatory; no fall-through
case "blue": b++; break;
case "green": g++; break;
default: other++; break; // break necessary on default
}
VB.NET
Loops
C#


Pre-test Loops:

While c < 10
c += 1
End While
Do Until c = 10
c += 1
Loop

Do While c < 10
c += 1
Loop
For c = 2 To 10 Step 2
Console.WriteLine(c)
Next


Post-test Loops:

Do
c += 1
Loop While c < 10
Do
c += 1
Loop Until c = 10

' Array or collection looping
Dim names As String() = {"Fred", "Sue", "Barney"}
For Each s As String In names
Console.WriteLine(s)
Next Pre-test Loops:
// no "until" keyword
while (i < 10)
i++;

for (i = 2; i < = 10; i += 2)
Console.WriteLine(i);


Post-test Loop:

do
i++;
while (i < 10);



// Array or collection looping
string[] names = {"Fred", "Sue", "Barney"};
foreach (string s in names)
Console.WriteLine(s);
VB.NET
Arrays
C#


Dim nums() As Integer = {1, 2, 3}
For i As Integer = 0 To nums.Length - 1
Console.WriteLine(nums(i))
Next

' 4 is the index of the last element, so it holds 5 elements
Dim names(4) As String
names(0) = "David"
names(5) = "Bobby" ' Throws System.IndexOutOfRangeException

' Resize the array, keeping the existing values (Preserve is optional)
ReDim Preserve names(6)


Dim twoD(rows-1, cols-1) As Single
twoD(2, 0) = 4.5

Dim jagged()() As Integer = { _
New Integer(4) {}, New Integer(1) {}, New Integer(2) {} }
jagged(0)(4) = 5 int[] nums = {1, 2, 3};
for (int i = 0; i < nums.Length; i++)
Console.WriteLine(nums[i]);


// 5 is the size of the array
string[] names = new string[5];
names[0] = "David";
names[5] = "Bobby"; // Throws System.IndexOutOfRangeException


// C# can't dynamically resize an array. Just copy into new array.
string[] names2 = new string[7];
Array.Copy(names, names2, names.Length); // or names.CopyTo(names2, 0);
float[,] twoD = new float[rows, cols];
twoD[2,0] = 4.5f;
int[][] jagged = new int[3][] {
new int[5], new int[2], new int[3] };
jagged[0][4] = 5;
VB.NET
Functions
C#


' Pass by value (in, default), reference (in/out), and reference (out)
Sub TestFunc(ByVal x As Integer, ByRef y As Integer, ByRef z As Integer)
x += 1
y += 1
z = 5
End Sub
Dim a = 1, b = 1, c As Integer ' c set to zero by default
TestFunc(a, b, c)
Console.WriteLine("{0} {1} {2}", a, b, c) ' 1 2 5
' Accept variable number of arguments
Function Sum(ByVal ParamArray nums As Integer()) As Integer
Sum = 0
For Each i As Integer In nums
Sum += i
Next
End Function ' Or use Return statement like C#

Dim total As Integer = Sum(4, 3, 2, 1) ' returns 10
' Optional parameters must be listed last and must have a default value
Sub SayHello(ByVal name As String, Optional ByVal prefix As String = "")
Console.WriteLine("Greetings, " & prefix & " " & name)
End Sub

SayHello("Strangelove", "Dr.")
SayHello("Madonna") // Pass by value (in, default), reference (in/out), and reference (out)
void TestFunc(int x, ref int y, out int z) {
x++;
y++;
z = 5;
}
int a = 1, b = 1, c; // c doesn't need initializing
TestFunc(a, ref b, out c);
Console.WriteLine("{0} {1} {2}", a, b, c); // 1 2 5
// Accept variable number of arguments
int Sum(params int[] nums) {
int sum = 0;
foreach (int i in nums)
sum += i;
return sum;
}
int total = Sum(4, 3, 2, 1); // returns 10
/* C# doesn't support optional arguments/parameters. Just create two different versions of the same function. */
void SayHello(string name, string prefix) {
Console.WriteLine("Greetings, " + prefix + " " + name);
}

void SayHello(string name) {
SayHello(name, "");
}
VB.NET
Strings
C#


Special character constants
vbCrLf, vbCr, vbLf, vbNewLine
vbNullString
vbTab
vbBack
vbFormFeed
vbVerticalTab
""

' String concatenation
Dim school As String = "Harding" & vbTab
school = school & "University" ' school is "Harding (tab) University"
' Chars
Dim letter As Char = school.Chars(0) ' letter is H
letter = Convert.ToChar(65) ' letter is A
letter = Chr(65) ' same thing
Dim word() As Char = school.ToCharArray() ' word holds Harding
' No string literal operator
Dim msg As String = "File is c:\temp\x.dat"



' String comparison
Dim mascot As String = "Bisons"
If (mascot = "Bisons") Then ' true
If (mascot.Equals("Bisons")) Then ' true
If (mascot.ToUpper().Equals("BISONS")) Then ' true
If (mascot.CompareTo("Bisons") = 0) Then ' true
Console.WriteLine(mascot.Substring(2, 3)) ' Prints "son"
' My birthday: Oct 12, 1973
Dim dt As New DateTime(1973, 10, 12)
Dim s As String = "My birthday: " & dt.ToString("MMM dd, yyyy")
Console.WriteLine(s)
' Mutable string
Dim buffer As New System.Text.StringBuilder("two ")
buffer.Append("three ")
buffer.Insert(0, "one ")
buffer.Replace("two", "TWO")
Console.WriteLine(buffer) ' Prints "one TWO three" Escape sequences
\n, \r
\t
\\
\"



// String concatenation
string school = "Harding\t";
school = school + "University"; // school is "Harding (tab) University"
// Chars
char letter = school[0]; // letter is H
letter = Convert.ToChar(65); // letter is A
letter = (char)65; // same thing
char[] word = school.ToCharArray(); // word holds Harding
// String literal
string msg = @"File is c:\temp\x.dat";
// same as
string msg = "File is c:\\temp\\x.dat";
// String comparison
string mascot = "Bisons";
if (mascot == "Bisons") // true
if (mascot.Equals("Bisons")) // true
if (mascot.ToUpper().Equals("BISONS")) // true
if (mascot.CompareTo("Bisons") == 0) // true
Console.WriteLine(mascot.Substring(2, 3)); // Prints "son"
// My birthday: Oct 12, 1973
DateTime dt = new DateTime(1973, 10, 12);
string s = "My birthday: " + dt.ToString("MMM dd, yyyy");
// Mutable string
System.Text.StringBuilder buffer = new System.Text.StringBuilder("two ");
buffer.Append("three ");
buffer.Insert(0, "one ");
buffer.Replace("two", "TWO");
Console.WriteLine(buffer); // Prints "one TWO three"
VB.NET
Exception Handling
C#


' Deprecated unstructured error handling
On Error GoTo MyErrorHandler
...
MyErrorHandler: Console.WriteLine(Err.Description)
' Throw an exception
Dim ex As New Exception("Something is really wrong.")
Throw ex
' Catch an exception
Try
y = 0
x = 10 / y
Catch ex As Exception When y = 0 ' Argument and When is optional
Console.WriteLine(ex.Message)
Finally
Beep()
End Try




// Throw an exception
Exception up = new Exception("Something is really wrong.");
throw up; // ha ha
// Catch an exception
try {
y = 0;
x = 10 / y;
}
catch (Exception ex) { // Argument is optional, no "When" keyword
Console.WriteLine(ex.Message);
}
finally {
// Must use unmanaged MessageBeep API function to beep
}
VB.NET
Namespaces
C#


Namespace Harding.Compsci.Graphics
...
End Namespace
' or
Namespace Harding
Namespace Compsci
Namespace Graphics
...
End Namespace
End Namespace
End Namespace
Imports Harding.Compsci.Graphics namespace Harding.Compsci.Graphics {
...
}
// or
namespace Harding {
namespace Compsci {
namespace Graphics {
...
}
}
}
using Harding.Compsci.Graphics;
VB.NET
Classes / Interfaces
C#


Accessibility keywords
Public
Private
Friend
Protected
Protected Friend
Shared
' Inheritance
Class FootballGame
Inherits Competition
...
End Class
' Interface definition
Interface IAlarmClock
...
End Interface
// Extending an interface
Interface IAlarmClock
Inherits IClock
...
End Interface
// Interface implementation
Class WristWatch
Implements IAlarmClock, ITimer
...
End Class Accessibility keywords
public
private
internal
protected
protected internal
static
// Inheritance
class FootballGame : Competition {
...
}

// Interface definition
interface IAlarmClock {
...
}
// Extending an interface
interface IAlarmClock : IClock {
...
}

// Interface implementation
class WristWatch : IAlarmClock, ITimer {
...
}
VB.NET
Constructors / Destructors
C#


Class SuperHero
Private _powerLevel As Integer

Public Sub New()
_powerLevel = 0
End Sub

Public Sub New(ByVal powerLevel As Integer)
Me._powerLevel = powerLevel
End Sub

Protected Overrides Sub Finalize()
' Desctructor code to free unmanaged resources
MyBase.Finalize()
End Sub
End Class class SuperHero {
private int _powerLevel;

public SuperHero() {
_powerLevel = 0;
}

public SuperHero(int powerLevel) {
this._powerLevel= powerLevel;
}

~SuperHero() {
// Destructor code to free unmanaged resources.
// Implicitly creates a Finalize method
}
}
VB.NET
Objects
C#


Dim hero As SuperHero = New SuperHero
With hero
.Name = "SpamMan"
.PowerLevel = 3
End With

hero.Defend("Laura Jones")
hero.Rest() ' Calling Shared method
' or
SuperHero.Rest()
Dim hero2 As SuperHero = hero ' Both refer to same object
hero2.Name = "WormWoman"
Console.WriteLine(hero.Name) ' Prints WormWoman
hero = Nothing ' Free the object
If hero Is Nothing Then _
hero = New SuperHero
Dim obj As Object = New SuperHero
If TypeOf obj Is SuperHero Then _
Console.WriteLine("Is a SuperHero object.") SuperHero hero = new SuperHero();

// No "With" construct
hero.Name = "SpamMan";
hero.PowerLevel = 3;
hero.Defend("Laura Jones");
SuperHero.Rest(); // Calling static method


SuperHero hero2 = hero; // Both refer to same object
hero2.Name = "WormWoman";
Console.WriteLine(hero.Name); // Prints WormWoman
hero = null ; // Free the object
if (hero == null)
hero = new SuperHero();
Object obj = new SuperHero();
if (obj is SuperHero)
Console.WriteLine("Is a SuperHero object.");
VB.NET
Structs
C#


Structure StudentRecord
Public name As String
Public gpa As Single

Public Sub New(ByVal name As String, ByVal gpa As Single)
Me.name = name
Me.gpa = gpa
End Sub
End Structure
Dim stu As StudentRecord = New StudentRecord("Bob", 3.5)
Dim stu2 As StudentRecord = stu

stu2.name = "Sue"
Console.WriteLine(stu.name) ' Prints Bob
Console.WriteLine(stu2.name) ' Prints Sue struct StudentRecord {
public string name;
public float gpa;

public StudentRecord(string name, float gpa) {
this.name = name;
this.gpa = gpa;
}
}
StudentRecord stu = new StudentRecord("Bob", 3.5f);
StudentRecord stu2 = stu;

stu2.name = "Sue";
Console.WriteLine(stu.name); // Prints Bob
Console.WriteLine(stu2.name); // Prints Sue
VB.NET
Properties
C#


Private _size As Integer

Public Property Size() As Integer
Get
Return _size
End Get
Set (ByVal Value As Integer)
If Value < 0 Then
_size = 0
Else
_size = Value
End If
End Set
End Property
foo.Size += 1 private int _size;

public int Size {
get {
return _size;
}
set {
if (value < 0)
_size = 0;
else
_size = value;
}
}

foo.Size++;
VB.NET
Delegates / Events
C#


Delegate Sub MsgArrivedEventHandler(ByVal message As String)
Event MsgArrivedEvent As MsgArrivedEventHandler
' or to define an event which declares a delegate implicitly
Event MsgArrivedEvent(ByVal message As String)
AddHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback
' Won't throw an exception if obj is Nothing
RaiseEvent MsgArrivedEvent("Test message")
RemoveHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback
Imports System.Windows.Forms
Dim WithEvents MyButton As Button ' WithEvents can't be used on local variable
MyButton = New Button
Private Sub MyButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyButton.Click
MessageBox.Show(Me, "Button was clicked", "Info", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub delegate void MsgArrivedEventHandler(string message);
event MsgArrivedEventHandler MsgArrivedEvent;
// Delegates must be used with events in C#


MsgArrivedEvent += new MsgArrivedEventHandler(My_MsgArrivedEventCallback);
MsgArrivedEvent("Test message"); // Throws exception if obj is null
MsgArrivedEvent -= new MsgArrivedEventHandler(My_MsgArrivedEventCallback);


using System.Windows.Forms;
Button MyButton = new Button();
MyButton.Click += new System.EventHandler(MyButton_Click);
private void MyButton_Click(object sender, System.EventArgs e) {
MessageBox.Show(this, "Button was clicked", "Info",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
VB.NET
Console I/O
C#


Console.Write("What's your name? ")
Dim name As String = Console.ReadLine()
Console.Write("How old are you? ")
Dim age As Integer = Val(Console.ReadLine())
Console.WriteLine("{0} is {1} years old.", name, age)
' or
Console.WriteLine(name & " is " & age & " years old.")

Dim c As Integer
c = Console.Read() ' Read single char
Console.WriteLine(c) ' Prints 65 if user enters "A" Console.Write("What's your name? ");
string name = Console.ReadLine();
Console.Write("How old are you? ");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("{0} is {1} years old.", name, age);
// or
Console.WriteLine(name + " is " + age + " years old.");

int c = Console.Read(); // Read single char
Console.WriteLine(c); // Prints 65 if user enters "A"
VB.NET
File I/O
C#


Imports System.IO
' Write out to text file
Dim writer As StreamWriter = File.CreateText("c:\myfile.txt")
writer.WriteLine("Out to file.")
writer.Close()
' Read all lines from text file
Dim reader As StreamReader = File.OpenText("c:\myfile.txt")
Dim line As String = reader.ReadLine()
While Not line Is Nothing
Console.WriteLine(line)
line = reader.ReadLine()
End While
reader.Close()
' Write out to binary file
Dim str As String = "Text data"
Dim num As Integer = 123
Dim binWriter As New BinaryWriter(File.OpenWrite("c:\myfile.dat"))
binWriter.Write(str)
binWriter.Write(num)
binWriter.Close()
' Read from binary file
Dim binReader As New BinaryReader(File.OpenRead("c:\myfile.dat"))
str = binReader.ReadString()
num = binReader.ReadInt32()
binReader.Close() using System.IO;
// Write out to text file
StreamWriter writer = File.CreateText("c:\\myfile.txt");
writer.WriteLine("Out to file.");
writer.Close();
// Read all lines from text file
StreamReader reader = File.OpenText("c:\\myfile.txt");
string line = reader.ReadLine();
while (line != null) {
Console.WriteLine(line);
line = reader.ReadLine();
}
reader.Close();
// Write out to binary file
string str = "Text data";
int num = 123;
BinaryWriter binWriter = new BinaryWriter(File.OpenWrite("c:\\myfile.dat"));
binWriter.Write(str);
binWriter.Write(num);
binWriter.Close();
// Read from binary file
BinaryReader binReader = new BinaryReader(File.OpenRead("c:\\myfile.dat"));
str = binReader.ReadString();
num = binReader.ReadInt32();
binReader.Close();

Operator Overloading
It is a design goal of C# that user-defined classes have all the functionality of built-in types. For example, suppose you have defined a type to represent fractions. Ensuring that this class has all the functionality of the built-in types means that you must be able to perform arithmetic on instances of your fractions (e.g., add two fractions, multiply, etc.) and convert fractions to and from built-in types such as integer (int). You could, of course, implement methods for each of these operations and invoke them by writing statements such as:
Fraction theSum = firstFraction.Add(secondFraction);
Although this will work, it is ugly and not how the built-in types are used. It would be much better to write:
Fraction theSum = firstFraction + secondFraction;
Statements like this are intuitive and consistent with how built-in types, such as int, are added.

In this chapter, you will learn techniques for adding standard operators to your user-defined types. You will also learn how to add conversion operators so that your user-defined types can be implicitly and explicitly converted to other types.
C# provides the ability to overload operators for your classes, even though this is not, strictly speaking, in the Common Language Specification (CLS). Other .NET languages, such as VB.NET, might not support operator overloading, and it is important to ensure that your class supports the alternative methods that these other languages might call to create the same effect.
Thus, if you overload the addition operator (+), you might also want to provide an add( ) method that does the same work. Operator overloading ought to be a syntactic shortcut, not the only path for your objects to accomplish a given task.
Operator overloading can make your code more intuitive and enable it to act more like the built-in types. It can also make your code unmanageable, complex, and obtuse if you break the common idiom for the use of operators. Resist the temptation to use operators in new and idiosyncratic ways.
For example, although it might be tempting to overload the increment operator (++) on an employee class to invoke a method incrementing the employee's pay level, this can create tremendous confusion for clients of your class. It is best to use operator overloading sparingly, and only when its meaning is clear and consistent with how the built-in classes operate.
Supported DbTypes for .NET only
The .NET Framework data provider type of a Parameter object is inferred from the .NET Framework type of the Value of the Parameter object, or from the DbType of the Parameter object. The following table shows the inferred Parameter type based on the object passed as the Parameter value or the specified DbType. You may specify the type of a Parameter in a generic fashion by setting the DbType property of the Parameter object to a particular System.Data.DbType.

CLR Type SqlDbType OleDbType OdbcType OracleType
Byte[] Binary, Image, VarBinary Binary, VarBinary Binary, Image, VarBinary Raw
Boolean Bit Boolean Bit Byte
Byte TinyInt - TinyInt Byte
DateTime DateTime, SmallDateTime Date Date, DateTime, SmallDateTime, Time DateTime
char Not supported Char Char Byte
Decimal Decimal, Money, SmallMoney Decimal, Currency, Numeric Decimal, Numeric Number
Double Float Double Double Double
Guid UniqueIdentifier Guid UniqueIdentifier Raw
Int16 SmallInt SmallIInt SmallInt Int16
Int32 Int Integer Int Int32
Int64 BigInt BigInt BigInt Number
Single Real Single Real Float
String Char, Nchar, NVarchar, Text, VarChar Char, VarChar Char, NChar, NText, NVarChar, Text, VarChar NVarChar
TimeSpan Not supported DBTime Time DateTime
UInt16 Int - - UInt16
UInt32 Decimal - - UInt32
UInt64 Decimal - - Number


In VB.NET, Short data type is 16 bit. In VB.NET, Short, Integer, and Long are equivalent to CLR’s System.Int16, System,Int32, and System.Int64 data types.

But BigInt in SQL server maps to int64 and Numeric maps to Decimal. So please check you datatypes accordingly.

Name Brief Description
DAO Data Access Objects The first object-oriented interface that exposed the Microsoft Jet database engine that allowed developers using Visual Basic to directly connect to Access tables and other databases using ODBC. It is ideal for small databases in local deployments and single-system applications.
RDO Remote Data Objects An object-oriented data access interface to ODBC combined with the easy functionality of DAO allowing an interface to almost all of ODBC´s low power and flexibility.
RDO can´t access Jet of ISAM databases in an efficient way. RDO provides the objects, properties, and methods needed to access the more complex aspects of stored procedures and complex resultsets.

ADO Microsoft ActiveX Data Objects ADO is the successor to DAO/RDO. ADO is the consolidation of almost all the functionality of DAO and RDO.
ADO mostly includes RDO-style functionality to interact with OLE DB data sources, plus remoting and DHTML technology.
ADO MD Microsoft ActiveX Data Objects Multidimensional Provides easy access to multidimensional data from languages such as Microsoft Visual Basic and Microsoft Visual C++. ADO MD extends Microsoft ActiveX Data Objects (ADO) to include objects specific to multidimensional data, such as the CubeDef and Cellset objects. To work with ADO MD, the provider must be a multidimensional data provider (MDP) as defined by the OLE DB for OLAP specification. MDPs present data in multidimensional views as opposed to tabular data providers (TDPs) that present data in tabular views. With ADO MD you can browse multidimensional schema, query a cube, and retrieve the results.
ADOX Microsoft ActiveX Data Objects Extensions for Data Definition Language and Security Is an extension to the ADO objects and programming model. ADOX includes objects for schema creation and modification, as well as security. Because it is an object-based approach to schema manipulation, you can write code that will work against various data sources regardless of differences in their native syntaxes.ADOX is a companion library to the core ADO objects. It exposes additional objects for creating, modifying, and deleting schema objects, such as tables and procedures. It also includes security objects to maintain users and groups and to grant and revoke permissions on objects.
RDS Remote Data Service
You can move data from a server to a client application or Web page, manipulate the data on the client, and return updates to the server in a single round trip.

ADO.NET Microsoft ActiveX Data Objects .NET ADO.NET is entirely based on XML. ADO.NET provides consistent access to data sources such as Microsoft SQL Server, as well as data sources exposed via OLE DB and XML. Data-sharing consumer applications can use ADO.NET to connect to these data sources and retrieve, manipulate, and update data.
ADO.NET cleanly factors data access from data manipulation into discrete components that can be used separately or in tandem. ADO.NET includes .NET data providers for connecting to a database, executing commands, and retrieving results. Those results are either processed directly, or placed in an ADO.NET DataSet object in order to be exposed to the user in an ad-hoc manner, combined with data from multiple sources, or remoted between tiers. The ADO.NET DataSet object can also be used independently of a .NET data provider to manage data local to the application or sourced from XML.
The ADO.NET classes are found in System.Data.dll, and are integrated with the XML classes found in System.Xml.dll. When compiling code that uses the System.Data namespace, reference both System.Data.dll and System.Xml.dll. Compared with ADO there is no Recordset object.
In ADO.NET there are four classes that read and write data from data sources:
1. Connection .- Connect to data source
2. Command .- Execute stored procedures
3. DataAdapter .- Connects DataSet to database
4. DataReader .- Forward/only, read/only cursor



What’s the implicit name of the parameter that gets passed into the class’ set method?

Value, and its datatype depends on whatever variable we’re changing.

How do you inherit from a class in C#?

Place a colon and then the name of the base class. Notice that it’s double colon in C++.

What happens when you encounter a continue statement inside the for loop?

The code for the rest of the loop is ignored, the control is transferred back to the beginning of the loop.

Does C# support multiple inheritance?

No, use interfaces instead.

When you inherit a protected class-level variable, who is it available to?

Classes in the same namespace.

Are private class-level variables inherited?

Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.

Describe the accessibility modifier protected internal.

It’s available to derived classes and classes within the same Assembly (and naturally from the base class it’s declared in).

C# provides a default constructor for me. I write a constructor that takes a string as a parameter, but want to keep the no parameter one. How many constructors should I write?

Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself, even if there’s no implementation in it.

What does the keyword virtual mean in the method definition?

The method can be over-ridden.

Can you declare the override method static while the original method is non-static?

No, you can’t, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.

Can you override private virtual methods?

No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access.

Can you prevent your class from being inherited and becoming a base class for some other classes?

Yes, that’s what keyword sealed in the class definition is for. The developer trying to derive from your class will get a message: cannot inherit from Sealed class WhateverBaseClassName. It’s the same concept as final class in Java.

Can you allow class to be inherited, but prevent the method from being over-ridden?

Yes, just leave the class public and make the method sealed.

What’s an abstract class?

A class that cannot be instantiated. A concept in C++ known as pure virtual method. A class that must be inherited and have the methods over-ridden. Essentially, it’s a blueprint for a class without any implementation.

When do you absolutely have to declare a class as abstract (as opposed to free-willed educated choice or decision based on UML diagram)?

When at least one of the methods in the class is abstract. When the class itself is inherited from an abstract class, but not all base abstract methods have been over-ridden.

What’s an interface class?

It’s an abstract class with public abstract methods all of which must be implemented in the inherited classes.

Why can’t you specify the accessibility modifier for methods inside the interface?

They all must be public. Therefore, to prevent you from getting the false impression that you have any freedom of choice, you are not allowed to specify any accessibility, it’s public by default.

Can you inherit multiple interfaces?

Yes.

And if they have conflicting method names?

It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay.

How can you overload a method?

Different parameter data types, different number of parameters, different order of parameters.

If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor?

Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.

What’s the difference between System.String and System.StringBuilder classes?

System.String is immutable; System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

What’s the advantage of using System.Text.StringBuilder over System.String?

StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it’s being operated on, a new instance is created.

Can you store multiple data types in System.Array?

No.

How can you sort the elements of the array in descending order?

By calling Sort() and then Reverse() methods.

What’s the .NET datatype that allows the retrieval of data by a unique key?

HashTable.

What’s class SortedList underneath?

A sorted HashTable.

Can multiple catch blocks be executed?

No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block.

Why is it a bad idea to throw your own exceptions? Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project.

What namespaces are necessary to create a localized application?

System.Globalization, System.Resources.

How do you generate documentation from the C# file commented properly with a command-line compiler?

Compile it with a /doc switch.

What’s the difference between and XML documentation tag?

Single line code example and multiple-line code example.

Is XML case-sensitive?

Yes, so and are different elements.

What debugging tools come with the .NET SDK?

CorDBG – command-line debugger, and DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR. To use CorDbg, you must compile the original C# file using the /debug switch.

What does the This window show in the debugger?

It points to the object that’s pointed to by this reference. Object’s instance data is shown.

What does assert() do?

In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.

Why are there five tracing levels in System.Diagnostics.TraceSwitcher?

The tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. Five levels range from None to Verbose, allowing to fine-tune the tracing activities.

Where is the output of TextWriterTraceListener redirected?

To the Console or a text file depending on the parameter passed to the constructor.

How do you debug an ASP.NET Web application?

Attach the aspnet_wp.exe process to the DbgClr debugger.

What is the wildcard character in SQL?

Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.

Explain ACID rule of thumb for transactions.

Transaction must be
Atomic (it is one unit of work and does not dependent on previous and following transactions),
Consistent (data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t),
Isolated (no transaction sees the intermediate results of the current transaction),
Durable (the values persist if the data had been committed even if the system crashes right after).

What does Dispose method do with the connection object?

Deletes it from the memory.

What is a pre-requisite for connection pooling?

Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings.

What is an abstract class?

A class that cannot be instantiated. A concept in C++ known as pure virtual method. A class that must be inherited and have the methods over-ridden. Essentially, it is a blueprint for a class without...

It is an abstract class with public abstract methods all of which must be implemented in the inherited classes.

Why cannot you specify the accessibility modifier for methods inside the interface?

They all must be public. Therefore, to prevent you from getting the false impression that you have any freedom of choice, you are not allowed to specify any accessibility, it is public by default.

In which Scenario you will go for Interface or Abstract Class?

Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes. Even though class inheritance allows your classes to inherit implementation from a base class, it also forces you to make most of your design decisions when the class is first published.

Abstract classes are useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. They also version well, because if additional functionality is needed in derived classes, it can be added to the base class without breaking code.


Interfaces vs. Abstract Classes
Feature Interface Abstract class
Multiple inheritance A class may implement several interfaces. A class may extend only one abstract class.
Default implementation An interface cannot provide any code at all, much less default code. An abstract class can provide complete code, default code, and/or just stubs that have to be overridden.
Constants Static final constants only, can use them without qualification in classes that implement the interface. On the other paw, these unqualified names pollute the namespace. You can use them and it is not obvious where they are coming from since the qualification is optional. Both instance and static constants are possible. Both static and instance intialiser code are also possible to compute the constants.
Third party convenience An interface implementation may be added to any existing third party class. A third party class must be rewritten to extend only from the abstract class.
is-a vs -able or can-do Interfaces are often used to describe the peripheral abilities of a class, not its central identity, e.g. an Automobile class might implement the Recyclable interface, which could apply to many otherwise totally unrelated objects. An abstract class defines the core identity of its descendants. If you defined a Dog abstract class then Damamation descendants are Dogs, they are not merely dogable. Implemented interfaces enumerate the general things a class can do, not the things a class is.
Plug-in You can write a new replacement module for an interface that contains not one stick of code in common with the existing implementations. When you implement the interface, you start from scratch without any default implementation. You have to obtain your tools from other classes; nothing comes with the interface other than a few constants. This gives you freedom to implement a radically different internal design. You must use the abstract class as-is for the code base, with all its attendant baggage, good or bad. The abstract class author has imposed structure on you. Depending on the cleverness of the author of the abstract class, this may be good or bad. Another issue that's important is what I call "heterogeneous vs. homogeneous." If implementors/subclasses are homogeneous, tend towards an abstract base class. If they are heterogeneous, use an interface. (Now all I have to do is come up with a good definition of hetero/homogeneous in this context.) If the various objects are all of-a-kind, and share a common state and behavior, then tend towards a common base class. If all they share is a set of method signatures, then tend towards an interface.
Homogeneity If all the various implementations share is the method signatures, then an interface works best. If the various implementations are all of a kind and share a common status and behavior, usually an abstract class works best.
Maintenance If your client code talks only in terms of an interface, you can easily change the concrete implementation behind it, using a factory method. Just like an interface, if your client code talks only in terms of an abstract class, you can easily change the concrete implementation behind it, using a factory method.
Speed Slow, requires extra indirection to find the corresponding method in the actual class. Modern JVMs are discovering ways to reduce this speed penalty. Fast
Terseness The constant declarations in an interface are all presumed public static final, so you may leave that part out. You can't call any methods to compute the initial values of your constants. You need not declare individual methods of an interface abstract. They are all presumed so. You can put shared code into an abstract class, where you cannot into an interface. If interfaces want to share code, you will have to write other bubblegum to arrange that. You may use methods to compute the initial values of your constants and variables, both instance and static. You must declare all the individual methods of an abstract class abstract.
Adding functionality If you add a new method to an interface, you must track down all implementations of that interface in the universe and provide them with a concrete implementation of that method. If you add a new method to an abstract class, you have the option of providing a default implementation of it. Then all existing code will continue to work without change.
Access Specifier We cannot mention any access specifier, all the method by default Public. As our requirement we can define the access specifier

see the code
interface ICommon
{
int getCommon();
}
interface ICommonImplements1:ICommon
{
}
interface ICommonImplements2:ICommon
{
}
public class a:ICommonImplements1,ICommonImplements2
{
}
How to implement getCommon method in class a? Are you seeing any problem in the implementation?
Ans:
public class a:ICommonImplements1,ICommonImplements2
{
public int getCommon()
{
return 1;
}
}
interface IWeather
{
void display();
}
public class A:IWeather
{
public void display()
{
MessageBox.Show("A");
}
}
public class B:A
{
}
public class C:B,IWeather
{
public void display()
{
MessageBox.Show("C");
}
}
When I instantiate C.display(), will it work?
interface IPrint
{
string Display();
}
interface IWrite
{
string Display();
}
class PrintDoc:IPrint,IWrite
{
//Here is implementation
}
how to implement the Display in the class printDoc (How to resolve the naming Conflict) A: no naming conflicts
class PrintDoc:IPrint,IWrite
{
public string Display()
{
return "s";
}
}
interface IList
{
int Count { get; set; }
}
interface ICounter
{
void Count(int i);
}
interface IListCounter: IList, ICounter {}
class C
{
void Test(IListCounter x)
{
x.Count(1); // Error
x.Count = 1; // Error
((IList)x).Count = 1; // Ok, invokes IList.Count.set
((ICounter)x).Count(1); // Ok, invokes ICounter.Count
}
}

Write one code example for compile time binding and one for run time binding? What is early/late binding?

An object is early bound when it is assigned to a variable declared to be of a specific object type. Early bound objects allow the compiler to allocate memory and perform other optimizations before an application executes.

' Create a variable to hold a new object.
Dim FS As FileStream

' Assign a new object to the variable.
FS = New FileStream("C:\tmp.txt", FileMode.Open)

By contrast, an object is late bound when it is assigned to a variable declared to be of type Object. Objects of this type can hold references to any object, but lack many of the advantages of early-bound objects.

Dim xlApp As Object
xlApp = CreateObject("Excel.Application")

Can you explain what inheritance is and an example of when you might use it?

How can you write a class to restrict that only one object of this class can be created (Singleton class)?

VB.Net

Public Class clsSingleton

Private Shared objSingle As clsSingleton
Private Shared blCreated As Boolean
Public strI As String

Private Sub New()
'Override the default constructor
End Sub

Public Shared Function getObject() As clsSingleton
If blCreated = False Then
objSingle = New clsSingleton()
blCreated = True
Return objSingle
Else
Return objSingle
End If
End Function

End Class

C#

For Singleton:

Public class classA
{
Private classA()

{

}
Private Static classA ObjA;
Private Static classA createInst()
{
If (ObjA != null)
{
ObjA = new classA();
Return objA;
}
Else
{
Return null;
}
}

For 10 objects :

Public class classA
{
Private static int count = 0;
Private classA()
{
Count ++;
}
Private Static classA ObjA;
Private Static classA createInst()
{
If (Count <= 10)
{
ObjA = new classA();
Return objA;
}
Else
{
Return null;
}
}

Will finally block get executed if the exception had not occurred?

Yes.

What is the C# equivalent of C++ catch (…), which was a catch-all statement for any possible exception?

Why would you use untrusted verificaion?

Web Services might use it, as well as non-Windows applications.

Why are there five tracing levels in System.Diagnostics.TraceSwitcher?

The tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. Five levels range from None to Verbo...

Which one is trusted and which one is untrusted?

Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participat...

Where is the output of TextWriterTraceListener redirected?

To the Console or a text file depending on the parameter passed to the constructor.

When you inherit a protected class-level variable, who is it available to?

Classes in the same namespace.

When do you absolutely have to declare a class as abstract (as opposed to free-willed educated choice or decision based on UML diagram)?

When at least one of the methods in the class is abstract. When the class itself is inherited from an abstract class, but not all base abstract methods have been over-ridden.

What namespaces are necessary to create a localized application?

System.Globalization, System.Resources.

What is the wildcard character in SQL?

Let us say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve La%.

What is the top .NET class that everything is derived from?

System.Object.

What is the implicit name of the parameter that gets passed into the class set method?

Value, and its datatype depends on whatever variable we are changing.

What is the difference between the System.Array.CopyTo() and System.Array.Clone()?

The first one performs a deep copy of the array, the second one is shallow.

What is the difference between the Debug class and Trace class?

Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.

What is the difference between System.String and System.StringBuilder classes?

System.String is immutable; System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it is being operated on, a new instance is created.

What is the difference between // comments, /* */ comments and /// comments?

Single-line, multi-line and XML documentation comments.

What is the data provider name to connect to Access database?

Microsoft.Access.

What is the .NET datatype that allows the retrieval of data by a unique key?

HashTable. What is class SortedList underneath?

What is a pre-requisite for connection pooling?

Multiple processes must agree that they will share the same connection, where every parameter is the same,

What is a delegate?

A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.

What is a multicast delegate?

It is a delegate that points to and eventually fires off several methods.

What does the This window show in the debugger?

It points to the object that is pointed to by this reference. Object’s instance data is shown.

What does the parameter Initial Catalog define inside Connection String?

The database name to connect to.

What does the keyword virtual mean in the method definition?

The method can be over-ridden.

What does Dispose method do with the connection object?

Deletes it from the memory.

What does assert() do?

In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true....

What debugging tools come with the .NET SDK?

CorDBG - command-line debugger, and DbgCLR - graphic debugger. Visual Studio .NET uses the DbgCLR. To use CorDbg, you must compile the original C# file using the /debug switch.

What connections does Microsoft SQL Server support?

Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords).

If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary base c...

Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.

How is method overriding different from overloading?

When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class.

How do you inherit from a class in C#?

Place a colon and then the name of the base class. Notice that it is double colon in C++.

How do you generate documentation from the C# file commented properly with a command-line compiler?

Compile it with a /doc switch.

How do you debug an ASP.NET Web application?

Attach the aspnet_wp.exe process to the DbgClr debugger.

How can you sort the elements of the array in descending order?

By calling Sort() and then Reverse() methods.

How can you overload a method?

Different parameter data types, different number of parameters, different order of parameters.

Explain the three services model (three-tier application).

Presentation (UI), business (logic and underlying code) and data (from storage or other sources).

Explain ACID rule of thumb for transactions.

Transaction must be Atomic (it is one unit of work and does not dependent on previous and following transactions), Consistent (data is either committed or roll back, no “in-between” case where someth...

Does C# support multiple inheritance?

No, use interfaces instead.

Describe the accessibility modifier protected internal.

It is available to derived classes and classes within the same Assembly (and naturally from the base class it is declared in).

Can you store multiple data types in System.Array?

No.

Can you prevent your class from being inherited and becoming a base class for some other classes?

Yes, that is what keyword sealed in the class definition is for. The developer trying to derive from your class will get a message: cannot inherit from Sealed class WhateverBaseClassName. It is the s...

Can you override private virtual methods?

No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access.

Can you inherit multiple interfaces?

Yes.

Can you declare the override method static while the original method is non-static?

No, you cannot, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.

Can you change the value of a variable while debugging a C# application?

Yes, if you are debugging via Visual Studio.NET, just go to Immediate window.

Can you allow class to be inherited, but prevent the method from being over-ridden?

Yes, just leave the class public and make the method sealed.

Can multiple catch blocks be executed?

No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block.

C# provides a default constructor for me. I write a constructor that takes a string as a parameter, but want to keep the no parameter one. How many constructors should I write?

Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself, even if there is no implementation in it.

Are private class-level variables inherited?

Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.

Why does DllImport not work for me?

All methods marked with the DllImport attribute must be marked as public static extern.

Why does my Windows application pop up a console window every time I run it?

Make sure that the target type set in the project properties setting is set to Windows Application, and not Console Application. If you're using the command line, compile with /...

Why do I get an error (CS1006) when trying to declare a method without specifying a return type?

If you leave off the return type on a method declaration, the compiler thinks you are trying to declare a constructor. So if you are trying to declare a method that returns noth...

Why do I get a syntax error when trying to declare a variable called checked?

The word checked is a keyword in C#.

Why do I get a security exception when I try to run my C# app?

Some security exceptions are thrown if you are working on a network share. There are some parts of the frameworks that will not run if being run off a share (roaming profile, ma...

Why do I get a "CS5001: does not have an entry point defined" error when compiling?

The most common problem is that you used a lowercase 'm' when defining the Main method. The correct way to implement the entry point is as follows:

class ...

What optimizations does the C# compiler perform when you use the /optimize+ compiler option?

The following is a response from a developer on the C# compiler team:

We get rid of unused locals (i.e., locals that are never read, even if assigned).

What is the syntax for calling an overloaded constructor within a constructor (this() and constructorname() does not compile)?

The syntax for calling another constructor is as follows:

class B

{

B(int i)

{ }

What is the equivalent to regsvr32 and regsvr32 /u a file in .NET development?

Try using RegAsm.exe. The general syntax would be: RegAsm. A good description of RegAsm and its associated switches is located in the .NET SDK docs. Just search on "Assembly Reg...


What is the difference between a struct and a class in C#?

From language spec:

The list of similarities between classes and structs is as follows.

Longstructs can implement interfaces and can...


My switch statement works differently! Why?

C# does not support an explicit fall through for case blocks. The following code is not legal and will not compile in C#: switch(x)

{

Is there regular expression (regex) support available to C# developers?


Yes. The .NET class libraries provide support for regular expressions. Look at the documentation for the System.Text.RegularExpressions namespace.

Is there an equivalent to the instanceof operator in Visual J++?

C# has the is operator:

expr is type


Is there an equivalent of exit() for quitting a C# .NET application?


Yes, you can use System.Environment.Exit(int exitCode) to exit the application or Application.Exit() if it's a Windows Forms app.

Is there a way to force garbage collection?

Yes. Set all references to null and then call System.GC.Collect().

If you need to have some objects destructed, and System.GC.Collect() doesn't seem to be ...

Is there a way of specifying which block or loop to break out of when working with nested loops?

The easiest way is to use goto: using System;
class BreakExample
{
public static void Main(String[] args)
...


Is it possible to restrict the scope of a field/method of a class to the classes in the same namespace?


There is no way to restrict to a namespace. Namespaces are never units of protection. But if you're using assemblies, you can use the 'internal' access modifier to restrict acce...

Is it possible to inline assembly or IL in C# code?

No.

Is it possible to have different access modifiers on the get/set methods of a property?

No. The access modifier on a property applies to both its get and set accessors. What you need to do if you want them to be different is make the property read-only (by only pro...

Is it possible to have a static indexer in C#?

No. Static indexers are not allowed in C#.

If I return out of a try/finally in C#, does the code in the finally-clause run?

Yes. The code in the finally always runs. If you return out of the try block, or even if you do a "goto" out of the try, the finally block always runs, as shown in the following...

I was trying to use an "out int" parameter in one of my functions. How should I declare the variable that I am passing to it?

You should declare the variable as an int, but when you pass it in you must specify it as 'out', like the following:

int i;

foo(out ...

How does one compare strings in C#?

In the past, you had to call .ToString() on the strings when using the == or != operators to compare the strings' values. That will still work, but the C# compiler now automatic...

How do you specify a custom attribute for the entire assembly (rather than for a class)?

Global attributes must appear after any top-level using clauses and before the first type or namespace declarations. An example of this is as follows: using System;

How do you mark a method obsolete?

Assuming you've done a "using System;": [Obsolete]

public int Foo() {...}

or [Obsolete("This is a message describing why this method ...

How do you implement thread synchronization (Object.Wait, Notify,and CriticalSection) in C#?

You want the lock statement, which is the same as Monitor Enter/Exit:

lock(obj)

{

// code

How do you directly call a native function exported from a DLL?

Here's a quick example of the DllImport attribute in action: using

System.Runtime.InteropServices;

class C

{

How do I simulate optional parameters to COM calls?

You must use the Missing class and pass Missing.Value (in System.Reflection) for any values that have optional parameters.

How do I register my code for use by classic COM clients?

Use the regasm.exe utility to generate a type library (if needed) and the necessary entries in the Windows Registry to make a class available to classic COM clients. Once a clas...

How do I port "synchronized" functions from Visual J++ to C#?

Original Visual J++ code: public synchronized void Run()

{

// function body

}

How do I make a DLL in C#?

You need to use the /target:library compiler option.

How do I do implement a trace and assert?


Use a conditional attribute on the method, as shown below:

class Debug

{

[conditional("TRACE")]


How do I declare inout arguments in C#?

The equivalent of inout in C# is ref. , as shown in the following

example: public void MyMethod (ref String str1, out String str2)

...


How do I create a multilanguage, single-file assembly?

This is currently not supported by Visual Studio .NET.

How do I create a multilanguage, multifile assembly?

Unfortunately, this is currently not supported in the IDE. To do this from the command line, you must compile your projects into netmodules (/target:module on the C# compiler), ...

How do I create a Delegate/MulticastDelegate?

C# requires only a single parameter for delegates: the method address. Unlike other languages, where the programmer must specify an object reference and the method to invoke, C#...

How do I convert a string to an int in C#?

Here's an example: using System;
class StringToInt
{
public static void Main()
{

How can I get the ASCII code for a character in C#?

Casting the char to an int will give you the ASCII value: char c = 'f';

System.Console.WriteLine((int)c);

or for a character in a str...

How can I get around scope problems in a try/catch?

If you try to instantiate the class inside the try, it'll be out of scope when you try to access it from the catch block. A way to get around this is to do the following:
...

How can I create a process that is running a supplied native executable (e.g., cmd.exe)?

The following code should run the executable and wait for it to exit before continuing: using System;

using System.Diagnostics;

...

How can I access the registry from C# code?

By using the Registry and RegistryKey classes in Microsoft.Win32, you can easily access the registry. The following is a sample that reads a key and displays its value: using Sy...

From a versioning perspective, what are the drawbacks of extending an interface as opposed to extending a class?

With regard to versioning, interfaces are less flexible than classes.

With a class, you can ship version 1 and then, in version 2, decide to add another m...

Does Console.WriteLine() stop printing when it reaches a NULL character within a string?

Strings are not null terminated in the runtime, so embedded nulls are allowed. Console.WriteLine() and all similar methods continue until the end of the string.


Does C# support try-catch-finally blocks?

Yes. Try-catch-finally blocks are supported by the C# compiler.

Here's an example of a try-catch-finally block: using System;

public...

Does C# support templates?

No. However, there are plans for C# to support a type of template known as a generic. These generic types have similar syntax but are instantiated at run time as opposed to comp...

Does C# support properties of array types?

Yes. Here's a simple example: using System;

class Class1

{

private string[] MyField;

Does C# support parameterized properties?

No. C# does, however, support the concept of an indexer from language spec.

An indexer is a member that enables an object to be indexed in the same way as...

Does C# support C type macros?

No. C# does not have macros. Keep in mind that what some of the predefined C macros (for example, __LINE__ and __FILE__) give you can also be found in .NET classes like

Does C# support #define for defining global constants?

No. If you want to get something that works like the following C code:

#define A 1

use the following C# code: class MyConstants

...

Can I define a type that is an alias of another type (like typedef in C++)?

Not exactly. You can create an alias within a single file with the "using" directive: using System;

using Integer = System.Int32; // alias

What is the difference between const and static read-only?

The difference is that static read-only can be modified by the containing class, but const can never be modified and must be initialized to a compile time constant. To expand on...

The C# keyword ‘int’ maps to which .NET type?

System.Int16
System.Int32
System.Int64
System.Int128

Which of these string definitions will prevent escaping on backslashes in C#?

string s = #”n Test string”;
string s = “’n Test string”;
string s = @”n Test string”;
string s = “n Test string”;

Which of these statements correctly declares a two-dimensional array in C#?

int[,] myArray;
int[][] myArray;
int[2] myArray;
System.Array[2] myArray;

If a method is marked as protected internal who can access it?

Classes that are both in the same assembly and derived from the declaring class.
Only methods that are in the same class as the method in question.
Internal methods can be only be called using reflection.
Classes within the same assembly, and classes derived from the declaring class.

What is boxing?

a) Encapsulating an object in a value type.
b) Encapsulating a copy of an object in a value type.
c) Encapsulating a value type in an object.
d) Encapsulating a copy of a value type in an object.

What compiler switch creates an xml file from the xml comments in the files in an assembly?

/text
/doc
/xml
/help


What is a delegate?

A strongly typed function pointer.
A light weight thread or process that can call a single method.
A reference to an object in a different process.
An inter-process message channel.

Which “Gang of Four” design pattern is shown below?

public class A
{
static private A instance;
private A()
{
}

static public A GetInstance()
{
if ( instance == null )
instance = new A();
return instance;
}
}

Factory

Abstract Factory

Singleton

Builder

11) In the NUnit test framework, which attribute must adorn a test class in order for it to be picked up by the NUnit GUI?

TestAttribute

TestClassAttribute

TestFixtureAttribute

NUnitTestClassAttribute

Which of the following operations can you NOT perform on an ADO.NET DataSet?

A DataSet can be synchronised with the database.
A DataSet can be synchronised with a RecordSet.
A DataSet can be converted to XML.
You can infer the schema from a DataSet.

In Object Oriented Programming, how would you describe encapsulation?

The conversion of one type of object to another.
The runtime resolution of method calls.
The exposition of data.
The separation of interface and implementation.

Are private class-level variables inherited?

Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.

Why does DllImport not work for me?

All methods marked with the DllImport attribute must be marked as public static extern. (more…)

Is it possible to inline assembly or IL in C# code?

No.

Is it possible to have different access modifiers on the get/set methods of a property?

No. The access modifier on a property applies to both its get and set accessors. What you need to do if you want them to be different is make the property read-only (by only providing a get accessor) and create a private/internal set method that is separate from the property.

Is it possible to have a static indexer in C#?

No. Static indexers are not allowed in C#.

If I return out of a try/finally in C#, does the code in the finally-clause run?

Yes. The code in the finally always runs. If you return out of the try block, or even if you do a “goto” out of the try, the finally block always runs:

using System;

class main
{
public static void Main()
{
try
{
Console.WriteLine(\"In Try block\");
return;
}
finally
{
Console.WriteLine(\"In Finally block\");
}
}
} Both “In Try block” and “In Finally block” will be displayed. Whether the return is in the try block or after the try-finally block, performance is not affected either way. The compiler treats it as if the return were outside the try block anyway. If it’s a return without an expression (as it is above), the IL emitted is identical whether the return is inside or outside of the try. If the return has an expression, there’s an extra store/load of the value of the expression (since it has to be computed within the try block).

I was trying to use an “out int” parameter in one of my functions. How should I declare the variable that I am passing to it?

You should declare the variable as an int, but when you pass it in you must specify it as ‘out’, like the following: int i; foo(out i); where foo is declared as follows: [return-type] foo(out int o) { }

How does one compare strings in C#?

In the past, you had to call .ToString() on the strings when using the == or != operators to compare the strings’ values. That will still work, but the C# compiler now automatically compares the values instead of the references when the == or != operators are used on string types. If you actually do want to compare references, it can be done as follows: if ((object) str1 == (object) str2) { … } Here’s an example showing how string compares work:
using System;
public class StringTest
{
public static void Main(string[] args)
{
Object nullObj = null; Object realObj = new StringTest();
int i = 10;
Console.WriteLine(\"Null Object is [\" + nullObj + \"]\n\"
+ \"Real Object is [\" + realObj + \"]\n\"
+ \"i is [\" + i + \"]\n\");
// Show string equality operators
string str1 = \"foo\";
string str2 = \"bar\";
string str3 = \"bar\";
Console.WriteLine(\"{0} == {1} ? {2}\", str1, str2, str1 == str2 );
Console.WriteLine(\"{0} == {1} ? {2}\", str2, str3, str2 == str3 );
}
}
Output:

Null Object is []
Real Object is [StringTest]
i is [10]
foo == bar ? False
bar == bar ? True

How do you specify a custom attribute for the entire assembly (rather than for a class)?

Global attributes must appear after any top-level using clauses and before the first type or namespace declarations. An example of this is as follows:
using System;
[assembly : MyAttributeClass] class X {}
Note that in an IDE-created project, by convention, these attributes are placed in AssemblyInfo.cs.

How do you mark a method obsolete? -
[Obsolete] public int Foo() {...}or
[Obsolete(\"This is a message describing why this method is obsolete\")] public int Foo() {...}Note: The O in Obsolete is always capitalized.

How do you implement thread synchronization (Object.Wait, Notify,and CriticalSection) in C#?

You want the lock statement, which is the same as Monitor Enter/Exit:
lock(obj) { // code }
translates to

try {
CriticalSection.Enter(obj);
// code
}
finally
{
CriticalSection.Exit(obj);

}

How do you directly call a native function exported from a DLL?

Here’s a quick example of the DllImport attribute in action:
using System.Runtime.InteropServices; \
class C
{
[DllImport(\"user32.dll\")]
public static extern int MessageBoxA(int h, string m, string c, int type);
public static int Main()
{
return MessageBoxA(0, \"Hello World!\", \"Caption\", 0);
}
}
This example shows the minimum requirements for declaring a C# method that is implemented in a native DLL. The method C.MessageBoxA() is declared with the static and external modifiers, and has the DllImport attribute, which tells the compiler that the implementation comes from the user32.dll, using the default name of MessageBoxA. For more information, look at the Platform Invoke tutorial in the documentation.

How do I simulate optional parameters to COM calls?

You must use the Missing class and pass Missing.Value (in System.Reflection) for any values that have optional parameters.

Difference between directcast and ctype?

DirectCast is used only when type of variable or object is same with the converting type used in met

The difference between the two keywords is that CType succeeds as long as there is a valid conversion defined between the expression and the type and DirectCast requires that the run-time type of an object variable to be the same as the specified type that it's being cast to. Really the same, not just that one can be converted to the other.

Use DirectCast if you're absolutely positively sure that an object is the specified type and the run-time type of the expression are the same. If you're not sure but expect that the conversion will work, use CType. The run-time performance of DirectCast is better than that of CType. However, DirectCast throws an InvalidCastException error if the argument types do not match, so you must be sure.

The difference between the two keywords is that CType succeeds as long as there is a valid conversion defined between the expression and the type, whereas DirectCast requires the run-time type of an object variable to be the same as the specified type. If the specified type and the run-time type of the expression are the same, however, the run-time performance of DirectCast is better than that of CType.

An example of a ctype and directcast?

ctype(123.34,integer) - should it throw an error? Why or why not?

Ctype is working with out any exception

directcast(123.34,integer) - should it throw an error? Why or why not?



Throwing error, seems ctype is much generic

Difference between a sub and a function.

Sub does not have return type
Difference between imperative and interrogative code.

What are the two kinds of properties.

What is the raise event used for?

What is a resource? Provide an example from your recent project.

What is a system lock?

Describe ways of cleaning up objects.

Where does the dispose method lie and how can it be used to clean up resources?

How can you clean up objects holding resources from within the code?

Write a program in C# for checking a given number is PRIME or not.

2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,

Write a C# program to find the Factorial of n

7! = 1 * 2 * 3 * 4 * 5 * 6 * 7 = 5040

Is goto statement supported in C#? How about Java?

Gotos are supported in C# to the fullest. In Java goto is a reserved keyword that provides absolutely no functionality.

What’s different about switch statements in C#?

No fall-throughs allowed. Unlike the C++ switch statement, C# does not support an explicit fall through from one case label to another. If you want, you can use goto a switch-case, or goto default.
case 1:
cost += 25;
break;
case 2:
cost += 25;
goto case 1;

Array list Examples

Dim Params As New ArrayList
Params.Add(New Pair("@shiftID", CStr(splitRow.ShiftID)))
Params.Add(New Pair("@shiftDate", CStr(splitRow.ShiftDate)))

logger.logError("Award Interpretation", "Award Interpretation exception in generating required processing data for " + splitRow.ShiftID.ToString() + " on " + splitRow.ShiftDate.ToString(), methodName, ex.Message & ex.Source)

HandleError("AWDAI00120", "Award Interpretation exception in generating required processing data for " + splitRow.ShiftID.ToString() + " on " + splitRow.ShiftDate.ToString(), methodName, ex.Message, iDeskErrorConstants.APPLICATION_ERROR, Params)

How to read the Resource file data?

using System.Resources;
private static System.Resources.ResourceManager go_bundle;
go_bundle.GetString(s_key);

go_bundle = ResourceManager.CreateFileBasedResourceManager
(IDeskConstantsIF.RESOURCE_BASE ,IDeskConstantsIF.CONFIG_FILENAME , null);

How to read the Registry data?

using System;
using Microsoft.Win32;
{
RegistryKey SUBKEY;
RegistryKey TAWKAY = RegistryKey.OpenRemoteBaseKey(Microsoft.Win32.RegistryHive.CurrentUser,"");
string subkey = "Software\\TAW\\BSE";
SUBKEY = TAWKAY.OpenSubKey(subkey);
object dsn = SUBKEY.GetValue("DSN");
object user = SUBKEY.GetValue("user");
object password = SUBKEY.GetValue("password");
object server = SUBKEY.GetValue("server");
return 0;
}

How to read the config file data?

using System.Configuration ;
public static string CONFIG_FILENAME = System.Configuration.ConfigurationSettings.AppSettings["configFile"];

Culture setting?

using System.Threading;
Thread.CurrentThread.CurrentCulture = new CultureInfo(locale);
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;

What is the difference between VB6 and VB.NET

There are quite a few differences in VB6 and VB.NET. We will highlight some of these here in points:

The greatest change in VB6 and VB.NET is of runtime environment. VB6 used the VB-Runtime while VB.NET uses the .Net Common Language Runtime (.Net CLR). The CLR is much better designed and implemented than VB-Runtime. The CLR uses better code translation through Just in Time compiler while VB-Runtime interprets the code. The CLR Garbage Collector is also more efficient than VB6 one as it may detect cyclic references too.

VB6 was interpreter based language while VB.NET is a compiled language

VB6 was not a type-safe language while VB.NET is a type safe language. There is no variant type in VB.NET and no magical type conversions happen in VB.NET

VB6 used ‘On Error Goto’ syntax to handle exceptions at runtime. VB.NET uses the Try…Catch…Finally syntax to handle exceptions at runtime.

A lot of code (like user interface code) in VB6 was hidden from developer. In VB.NET no code is hidden from developer and you can access and control each part of your application

VB.NET has much enhanced object oriented support than VB6

VB6 does not allow developing the multithreaded applications. In VB.NET you can create multithreaded applications.

VB6 was only considered good for desktop windows application. In VB.NET you can also develop web applications, distributed applications, create .NET windows and web controls and components, write windows and web services.

In VB.NET, you can also use reflections to read the meta-data of types and using reflection emit you can also generate code to define and invoke types at runtime.

VB.NET uses .NET framework class library along with specialized VB library (System.VisualBasic) as a standard library. As a result, the standard library for VB.NET is much enhanced and useful compared to VB6 standard library

VB.NET is platform independent because of .Net framework. Programs written in VB.NET can run on any platform where .Net framework is present. The platform include both hardware and software (operating system) platforms.

VB.NET also supports language interoperability with various .NET compliant languages. This means that you can use and enhance the code written in other .NET compliant languages. Similarly the code written in VB.NET can also be used and enhanced by other .NET compliant languages. Although VB6 also provided this functionality through COM but it was limited and difficult to use and manage. VB.Net makes it easier because of the presence of Intermediate Language (IL) and Common Language Specification (CLS) of the .NET architecture.

VB6 uses COM (Component Object Model) as component architecture. VB.NET uses assemblies as its component architecture. The Assemblies architecture has removed a lot of problems with COM including DLL-Hell and versioning problem.

Components created in VB6 (COM) need to make and update registry entries. VB.NET does not require any registry entry making the deployment easier

VB6 used ASP to build web applications. VB.NET uses ASP.NET to build web applications.

VB6 used ADODB and record-sets to implement data access applications. VB.NET uses ADO.NET and datasets to build data access applications. The ADO.NET also supports the disconnected data access.

What is the importance of the Option statement?

The Option statement is used to prevent syntax and logical errors in code. The possible suffixes of this statement are:

Option Explicit: Is the default abd is On. Option Explicit requires declaration of all variables before they are used.
Option Compare: This can be set to Binary or Text and it specifies if stringsp are to be compared using binary or text comparison operations.
Option Strict: The default is Off. An example: If value of one data type is assigned to another then Visual Basic will consider that as an error. If you want to assign a value of one Type to another then you should set it to On and use the conversion functions.
Example using the Option Statement.

The following code does not perform any special function but will show where to place an Option statement.

Option Strict Off
Imports System
Module Module 1
Sub Main ()
Console.WriteLine (“Using Option”)
End Sub
End Module

How do I convert text from lower case to upper case in VB.NET?

The following code shows how text can be converted from lower case to upper.

Module Module1
Sub Main ()
Dim str1 as String=”Welcome to String”
Dim str2 as String
Str2=UCase(str1)
Or
Str2=Str1.ToUpper
System.Console.WriteLine(str2)
End Sub

How do I handle Math functions in VB.NET?

Higher Mathematical functions in VB.NET are in the methods of the System.Math namespace. Calculation of a hyperbolic cosecant value and so on is possible by using the methods in this namespace.

Example using a Math Function

Imports System.Math
Module Module1
Sub Main()
System.Console.WiteLine(“Pi = “ & 4 * Atan())
End Sub
End Module

The output of the above code will be “ Pi = 3.141592…

How do I handle Date and Time in VB.NET?

Working with Dates is one to think about. Especially if your data needs to be spread accross timezones Also there are different date formats to take in to consideration. VB.NET Has some good Date() Functions, one of which is demonstrated below:

Example

Imports System.Math
Module Module1
Sub Main ()
Dim Dts as Date
Dts = # 10/15/2001
System.Console.WriteLine(“New Date: & DateAdd(DateInterval.Month, 22, Dts))
End Sub
End Module

The above code adds 22 months to the date we declared in the Program.

How do I create Procedure Delegates?

Delegates are used to work with the address of procedures. This is much like pointers in C and C++. Sometimes it's useful to pass the location of a procedure to other procedures.

Example working with Delegates:

Module Module1

Delegate Sub SubDelegate1(ByVal str as String)

Sub Main()

Dim Mess as SubDelegate1
Mess=AddressOf Display
Mess.Invoke(“Hello from Delegates”)

End Sub

Sub Display(ByVal str as String)

System.Console.WriteLine(StrText)

End Sub

End Module

The above code displays “Hello from Delegates” just like a normal program but it uses Delegates to do it.

How do I use the InputBox Function?

An InputBox function is much like a ?JavaScript prompt window which allows the input of text. To work with the InputBox, drag a Command Button and a TextBox from the Toolbar. Opon clicking the Command Button the InputBox prompts asks for a name. Once entered, press OK. That text will now be displayed in the Textbox.

The sample code for the click event


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles Button1.Click
Dim Show As String
Show = InputBox("Enter your name")
TextBox1.Text = Show
End Sub

How do I write data to a text file in VB.NET?

The following code creates a text file and inserts some text.

Imports System.IO
Public Class Form1 Inherits System.Windows.Forms.Form
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles MyBase.Load
Dim fs as New FileStream("exp.txt",FileMode.Create,FileAccess.Write)
Dim s as new StreamWriter(fs)
s.BaseStream.Seek(0,SeekOrigin.End)
s.WriteLine("ProgrammersHeaven has lot of programming goodies")
s.WriteLine(" good resource for most popular programming languages")
s.Close()
End Sub
End Class

How to get computer name and IP address?

The following code uses the System.NET.DNS namespace to access the "computer name" and it's IP address.

Option Strict Off
Imports system
Imports System.Net.DNS
Public Class GetIP

Shared Function GetIPAddress() As String
Dim sam As System.Net.IPAddress
Dim sam1 As String

With system.Net.DNS.GetHostByName(system.Net.DNS.GetHostName())
sam = New System.Net.IPAddress(.AddressList(0).Address)
sam1 = sam.ToString
End With

GetIPAddress = sam1

End Function

Shared Sub main()
Dim shostname As String
shostname = system.Net.DNS.GetHostName
console.writeline("Name of the System is = " & shostname)
console.writeline("Your IP address is= " & GetIPAddress)
End Sub

End Class

Compile the file as "vbc getip.vb /r:system.net.dll"

Execute the "getip.exe". The computer's name and IP address will be displayed in the Console.

Jagged Array

A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array-of-arrays."

//Decalaring a Jagged Array

int[][] myJaggedArray = new int[3][];

How to get the environment information in VB.NET?
The System.Environment namespace includes the functionality to get the environment information such as the UserName and OS Version.

File name is SystemInfo.vb

Imports System

Class SystemInfo

Shared Sub main()

Console.WriteLine("")
Console.WriteLine("Current User")
Console.WriteLine(Environment.UserName)
Console.WriteLine("")

Console.WriteLine("Name of the Machine")
Console.WriteLine(Environment.MachineName)
Console.WriteLine("")

Console.WriteLine("OS version")
Console.WriteLine(Environment.OSVersion)
Console.WriteLine("")

Console.WriteLine("System Directory")
Console.WriteLine(Environment.SystemDirectory)
Console.WriteLine("")

Console.WriteLine("TMP Folder")
Console.WriteLine(Environment.GetEnvironmentVariable("TMP"))
Console.WriteLine("")

Console.WriteLine("Class Path")
Console.WriteLine(Environment.GetEnvironmentVariable("ClassPath"))
Console.WriteLine("")
Console.readLine()
End Sub
End Class


How do I read and write data to an XML file?

The following code demonstrates how to read and write to an XML file.





Sandeep
23
Developer



Imports System
Class WriteToXML

Shared Sub main()
Dim dset As New System.Data.DataSet()
Dim str As String = "Test.xml"
'Load the XML file in the data set
dset.ReadXml("Test.xml")
'Read the XML content on the console
Console.Write(dset.GetXml)
'Getting data from the user to be saved into the XML file
Console.Write("Enter Name : ")
Dim name, age, occupation As String
name = Console.ReadLine
Console.Write("Enter Age : ")
age = Console.ReadLine
Console.Write("Enter Occupation : ")
occupation = Console.ReadLine
Console.Write(name & age & occupation)
Dim v(1) As String
v(0) = fname
v(1) = age
v(2)=occupation
dset.Tables(0).Rows.Add(v)
dset.WriteXml("Test.xml")
Console.Write(dset.GetXml)
End


When you run this code, the data from the XML file will be displayed. Also the data you enter will be updated into the XML file.

How to work with an interface in VB.NET?

The following code demonstrates the ability to work with an interface. An interface defines a method's name and not it's contents.

Imports System
Imports Microsoft.VisualBasic

Public Interface NewInt

Sub Mysub()
Function MyFun() As String

End Interface

Class myclass Implements MyInt
‘Implementing the above defined interface,
‘need to use the keyword implements to use the interface

Shared Sub Main()
Dim mc As New myclass()
mc.Mysub()
End Sub

Sub Mysub() Implements NewInt.Mysub
MsgBox("Hello from INterfaces")
End Sub

Function MyFun() As String Implements NewInt.MyFun
dim str as string
str="hello matey"
return (str)
End Function

End Class

How to convert the format of images in VB.NET?

To convert the format of an image you need to use the System.Drawing namespace. Using this code you can convert to a variety of graphic file formats, such as GIF or JPG.

The following example converts a user prompted Bitmap image file into .Gif format.

File ImageConverter.vb

Imports System
Imports System.Drawing

Class ConvertImages
Shared Sub main()
Dim str As String
Console.Write("Path of the Image File to Convert :")
str = Console.ReadLine()
'Initialize the bitmap object by supplying the image file path
Dim bmp As New Bitmap(str)
bmp.Save(str + ".gif", System.Drawing.Imaging.ImageFormat.Gif)
Console.Write("Image Sucessfully Converted to " & str & ".gif")
End Sub
End Class

What is the concept of destructors in VB.NET?

Destructors are used to de-allocate resources i.e. to clean up after an object is no longer available.

Finalize is the destructor which is normally used. Finalize is called automatically when the .NET runtime determines that the object is no longer being used. Using the Finalize method in code looks like this:


Public Class Form1 Inherits System.Windows.Forms.Form

Dim obj1 as new Class1 ()

End Class

Public Class Dest
Protected overrides Sub Finalize()
‘ calling the Finalize method
End Sub

End Class

How do I get Version Information From The AssemblyInfo File?

To get version information at Runtime in VB .NET, use the following code:

Function Version() As String With _

System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly.Location)
Return .FileMajorPart & "." & .FileMinorPart & "." & .FileBuildPart & "." & .FilePrivatePart
End With
End Function

Function Display() As String
With System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly.Location)
Return .Comments
End With
End Function

Upon running the version information of the Assembly file is displayed.

How can I run a .EXE from a VB.NET application?

To run a .EXE file from a VB.NET application you need to import the System.Diagnostics namespace. The following sample shows how to run Notepad from a VB.NET application.

Imports System
Imports System.Diagnostics

Dim program As New Process()
program.StartInfo.FileName = "Notepad.exe"
program.StartInfo.Arguments = " "
program.Start()

What is Try- Catch –Finally Exception Handling?

Exceptions are Runtime errors that occur when an unexpected process causes the program to abort. Such kind of situations can be kept at bay using Exception Handling. By looking for potential problems in the code / entity life cycle, we can handle most of the errors that may encountered. As a result the application to continue to run without being dogged by errors. VB.NET supports Structured exception handling by using Try...Catch...Finally

The following code sample demonstrates how to use Try-Catch-Finally exception handling.

Module Module1

Sub Main()
Dim a=0, b=1, c As Integer
Try
c=b / a
'the above line throws an exception
System.Console.WriteLine("C is " & c)
Catch e As Exception

System.Console.WriteLine(e)
'catching the exception

End Try
System.Console.Read()

End Sub
End Module

The output of the above code displays a message stating the exception. The reason for the exception is because any number divided by zero is infinity.

What is Anchoring and Docking?

The VB terms Docking and Anchoring are used to make sure that a control covers the whole client area of a form.

Upon "docking" a window, it adheres to the edges of it's container (the Form). To "dock" a particular control, select the Dock property of the control from the properties window.

Selecting the Dock property opens up a small window like structure where you can select towards which side on the Form should the control be docked.

You can use Anchoring to "anchor" a control to the edges of it’s container (the Form). Selecting this property in the properties window opens up a small window from where you can select what edge to "anchor" the control to.

How do I convert one DataType to other using the CType Function?

The CType is pretty generic conversion Function.

The example below demonstrates using a CType Function to convert a Double value to an Integer value.

Module Module1

Sub Main()
Dim d As Double

d = 132.31223

Dim i As Integer

i = CType(d, i)
'two arguments, type we are converting from, to type desired
System.Console.Write("Integer value is" & i)

End Sub
End Module

[VB.Net] Advantages of VB.NET
1. First of all, VB.NET provides managed code execution that runs under the Common Language Runtime (CLR), resulting in robust, stable and secure applications. All features of the .NET framewo...

[VB.Net] Advantages of migrating to VB.NET

Visual Basic .NET has many new and improved language features — such as inheritance, interfaces, and overloading — that make it a powerful object-oriented programming language. As ...

[VB.Net] What is the difference between VB 6 and VB.NET?

VB.NET is a very different animal from VB

The idea of VB.NET is that it should run on the .NET platform, which is a huge support library (as is Win32)
There are a number of other languages that do/will run on the .NET platform

This platform is designed to be (to some extent) hardware independant, so the languages are semi compiled, then properly compiled using JIT on the users machine

On can think of .NET as a massive Java Engine

VB6 is a language that runs directly on Win32, sure it needs a run time support DLL - MSVBVM60.DLL but that is trivial compared with the ..NET requirements

It is possible that .NET will become wide spread, at present it is in its infancy.
It is also possible that people writing other than massive corporate systems will ignore .NET

Personally I prefer to stay away from the 'bleeding edge' of new technology - as do most others in this NG

VB.NET is designed by a guy poached from Borland - the guy who designed Delphi - I've not looked that closely at VB.NET, but my understanding is that he has 'imported' a lot of concepts from Delphi, that are not present in VB6

I suspect that a competent programmer who understands VB6 would find it relatively easy to migrate to VB.NET

However to 'learn' VB in the first place is quite a step, and there is a lot more to VB than meets the eye.

[C#] using directive vs using statement

You create an instance in a using statement to ensure that Dispose is called on the object when the using statement is exited. A using statement can be exited either when the end of the using statement is reached or if, for example, an exception is thrown and control leaves the statement block before the end of the statement.
The using directive has two uses:
• Create an alias for a namespace (a using alias).
• Permit the use of types in a namespace, such that, you do not have to qualify the use of a type in that namespace (a using directive).

Example

using (MyManagedClass mnObj = new MyManagedClass())
{

mnObj.Use(); //use the mnObj object

} //The compiler will dispose the mnObj object now

Your Title