You are on page 1of 33

Some differences between Java and C#:

C# provides more data types as compared to Java.


C# contains more primitive data types than Java.
C# supports operator overloading while Java does not.
C# supports the strut type while Java does not.
AII data types in C# are strut.
C# provides better versioning than Java.
C# allows parameters to be passed by reference by using the ref keyword, whereas Java allows
parameters to be passed by value.
C# allows variable number of parameters using the param keyword.
C# provides static constructors for initialization.
C# provides goto statement instead of the break statement.
Declaration of arrays is different in C# as compared to Java.
The convention for Java is to put one public class in each file and some compilers require this. C#
allows any source file arrangement.
Java does not support events and delegates.
In Java, methods are virtual by default but can be made final. While, in C# they're sealed by default, but
can be made virtual.
C# doesn't have checked exceptions.
Java doesn't allow the creation of user-defined value types.
Java doesn't have operator and conversion overloading.
Java doesn't have iterator blocks for simple implemetation of iterators.
Java doesn't have anything like LINQ.
Partly due to not having delegates, Java doesn't have anything quite like anonymous methods and
lambda expressions.
Java doesn't have expression trees.
C# doesn't have anonymous inner classes.
Java doesn't have implicitly typed local variables.
Java doesn't have extension methods.
Java doesn't have properties as part of the language; they're a convention of get/set/is methods.
Java doesn't have the equivalent of "unsafe" code.
Java's enums are much more object-oriented.
Java has no preprocessor directives (#define, #if etc in C#).
Java has no equivalent of C#'s ref and out for passing parameters by reference.
C# interfaces cannot declare fields.
Java has no unsigned integer types.
Java has no language support for a decimal type.
Java has no equivalent of nullable value types

Extension methods enable you to "add" methods to existing types without creating a new derived type,
recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method,
but they are called as if they were instance methods on the extended type. For client code written in C# and
Visual Basic, there is no apparent difference between calling an extension method and the methods that are
actually defined in a type.
A delegate is a class that can hold a reference to a method. Unlike other classes, a delegate class has a
signature, and it can hold references only to methods that match its signature. A delegate is thus equivalent to
a type-safe function pointer or a callback. While delegates have other uses, the discussion here focuses on the
event handling functionality of delegates. A delegate declaration is sufficient to define a delegate class. The
declaration supplies the signature of the delegate, and the common language runtime provides the
implementation. The following example shows an event delegate declaration.

With the introduction of the .NET framework, Microsoft included a new language called C# (pronounced C
Sharp). C# is designed to be a simple, modern, general-purpose, object-oriented programming language,
borrowing key concepts from several other languages, most notably Java.

C# could theoretically be compiled to machine code, but in real life, it's always used in combination with the
.NET framework. Therefore, applications written in C#, requires the .NET framework to be installed on the
computer running the application. While the .NET framework makes it possible to use a wide range of
languages, C# is sometimes referred to as THE .NET language, perhaps because it was designed together with
the framework.

C# is an Object Oriented language and does not offer global variables or functions. Everything is wrapped in
classes, even simple types like int and string, which inherits from the System. Object class C# can be written
with any text editor, like Windows Notepad, and then compiled with the C# Command line compiler, csc.exe,
which comes with the .NET framework. However, most people prefer to use an IDE (Integrated Development
Environment), and Microsoft offers several options for this. Their flagship is Visual Studio, which can be used
to work on every possible aspect of the .NET framework. This product is very advanced, and comes in several
editions. Visual Studio is not exactly cheap, and might even be too advanced for hobby programmers.

With .NET framework 2.0, Microsoft introduced the so-called Express versions, targeted at hobby programmers
and people wanting to try .NET, and they continued this tradition with the later release of .NET 3.0 and 3.5. The
Express versions only work for one language, like C# or VB.NET, and miss some of the really advanced
features of Visual Studio.
C# based on key points in the following sections:
Simple
Modern
Object-oriented
Type-safe
Versionable
Compatible
Flexible
Simple
Pointers are a prominent feature that is missing in C#. By default, you are working with managed code, where
unsafe operations, such as direct memory manipulation, are not allowed. I don't think any C++ programmer can
claim never to have accessed memory that didn't belong to him via a pointer.
In C++, you have ::, ., and -> operators that are used for namespaces, members, and references. For a beginner,
operators make for yet another hard day of learning. C# does away with the different operators in favor of a
single one: the . (the "dot"). All that a programmer now has to understand is the notion of nested names.
C# provides a unified type system. This type system enables you to view every type as an object, be it a
primitive type or a full-blown class. In contrast to other programming languages, treating a simple type as an
object does not come with a performance penalty because of a mechanism called boxing and unboxing. Boxing
and unboxing is explained later in detail, but basically, this technique provides object access to simple types
only when requested.
Integer and Boolean data types are now two entirely different types. That means a mistaken assignment in an if
statement is now flagged as an error by the compiler because it takes a Boolean result only. No more
comparison-versus-assignment errors!
C# also gets rid of redundancies that crept into C++ over the years. Such redundancies include, for example,
const versus #define, different character types, and so on. Commonly used forms are available in C#, whereas
the redundant forms were eliminated from the language.
Modern
C# was designed to be the premier language for writing NGWS (Next Generation Windows Services)
applications. You will find many features that you had to implement yourself in C++, or that were simply
unavailable.
You get a new decimal data type that is targeted at monetary calculations. You can easily create new ones
specifically crafted for your application.
The entire memory management is no longer your dutythe runtime of NGWS provides a garbage collector
that is responsible for memory management in your C# programs. Because memory and your application are
managed, it is imperative that type safety be enforced to guarantee application stability.
Exception handling is a main feature of C#. The difference from C++, however, is that exception handling is
cross-language (another feature of the runtime).
Security is a top requirement for a modern application. C# provides metadata syntax for declaring capabilities
and permissions for the underlying NGWS security model. Metadata is a key concept of the NGWS runtime,
and the next chapter deals with its implications in more depth.
Object-Oriented
C#, of course, supports all the key object-oriented concepts such as encapsulation, inheritance, and
polymorphism. The entire C# class model is built on top of the NGWS (Next Generation Windows Services)
runtime's Virtual Object System (VOS), which is described in the next chapter. The object model is part of the
infrastructure, and is no longer part of the programming language.
There are no more global functions, variables, or constants. Everything must be encapsulated inside a class,
either as an instance member (accessible via an instance of a classan object) or a static member (via the type).
This makes your C# code more readable and also helps to reduce potential naming conflicts.
The methods you can define on classes are, by default, non virtual (they cannot be overridden by deriving
classes). The main point of this is that another source of errors disappearsthe accidental overriding of
methods. For a method to be able to be overridden, it must have the explicit virtual modifier. This behavior not
only reduces the size of the virtual function table, but also guarantees correct versioning behavior.
C# also supports the private, protected, and public access modifiers, and also adds a fourth one: internal. Details
about these access modifiers are presented in Chapter 5, "Classes."
C# allows only one base class. For multiple inheritance, you can implement interfaces.
A question that might come up is how to emulate function pointers when there are no pointers in C#. The
answer to this question is delegates, which provide the underpinnings for the NGWS runtime's event model.
Type-Safe
C# implements strictest type safety to protect itself and the garbage collector. Therefore, you must abide by a
few rules in C# with regard to variables:
You cannot use uninitialized variables. For member variables of an object, the compiler takes care of
zeroing them. For local variables, you are incharge. However, if you use an uninitialized variable, the
compiler will tell you so. The advantage is that you get rid of those errors when using an uninitialized
variable to compute a result and you don't know how these funny results are produced.
C# does away with unsafe casts. You cannot cast from an integer to a reference type (object, for
example), and when you downcast, C# verifies that this cast is okay. (That is, that the derived object is
really derived from the class to which you are down casting it.)
Bounds checking is part of C#. It is no longer possible to use that "extra" array element n, when the
array actually has n-1 elements. This makes it impossible to overwrite unallocated memory.
Arithmetic operations could overflow the range of the result data type. C# allows you to check for
overflow in such operations on either an application level or a statement level. With overflow checking
enabled, an exception is thrown when an overflow happens.
Reference parameters that are passed in C# are type-safe.
Versionable
The problem stems from the fact that multiple applications install different versions of the same DLL to the
computer. Sometimes, older applications happily work with the newer version of the DLL; however, most of
the time, they break. Versioning is a real pain today.
"Writing Components in C#," the versioning support for applications you write is provided by the NGWS
runtime. C# does its best to support this versioning. Although C# itself cannot guarantee correct versioning, it
can ensure that versioning is possible for the programmer. With this support in place, a developer can guarantee
that as his class library evolves, it will retain binary compatibility with existing client applications.
Compatible
C# allows you access to different APIs, with the foremost being the NGWS Common Language Specification
(CLS). The CLS defines a standard for interoperation between languages that adhere to this standard. To
enforce CLS compliance, the compiler of C# checks that all publicly exported entities comply, and raises an
error if they do not.
Of course, you also want to be able to access your older COM objects. The NGWS runtime provides transparent
access to COM
The good news is that C# supports OLE Automation, without bothering you with details.
Finally, C# enables you to inter operate with C-style APIs. Any entry point in a DLLgiven its C-styledness
is accessible from your applications. This feature for accessing native APIs is called Platform Invocation
Services (Pinvoke).
Flexible
The last paragraph of the previous section might have raised an alert with C programmers. You might ask,
"Aren't there APIs to which I have to pass a pointer?" You are right. There are not only a few such APIs, but
quite a large number (a small understatement). This access to native WIN32 code sometimes makes using
unsafe classic pointers mandatory (although some of it can be handled by the support of COM and PInvoke).
Although the default for C# code is safe mode, you can declare certain classes or only methods of classes to be
unsafe. This declaration enables you to use pointers, structs, and statically allocated arrays. Both safe code and
unsafe code run in the managed space, which implies that no marshaling is incurred when calling unsafe code
from safe code.
What are the implications of dealing with your own memory in unsafemode? Well, the garbage collector, of
course, may not touch your memory locations and move them just as it does for managed code. Unsafe
variables are pinned into the memory block managed by the garbage collector.

difference between C++ and C#
C# is a distinct language from C++. C++ is designed for general object oriented programming in the days when
the typical computer was a standalone machine running a command line-based user interface. C++ is a general-
purpose programming language with high-level and low-level capabilities. It is a statically typed, free-form,
multi-paradigm, usually compiled language supporting procedural programming, data abstraction, object-
oriented programming, and generic programming.
C++ is regarded as a mid-level language. This indicates that C++ comprises a combination of both high-level
and low-level language features. C# is designed specifically to work with the .Net and is geared to the modern
environment of Windows and mouse-controlled user interface, networks and the internet.
Microsoft has defined C# as follows

C# is a simple, modern, object oriented, and type-safe programming language derived from C and C++. C#
(pronounced C sharp) is firmly planted in the C and C++ family tree of languages, and will immediately be
familiar to C and C++ programmers. C# aims to combine the high productivity of Visual Basic and the raw
power of C++.

However it is also undeniable that the two languages are very similar in both their syntax and in that they are
both designed to facilitate the same paradigm of programming, in which code is based around hierarchies of
inherited classes.

Environment

C++ was designed to be a low-level platform-neutral object-oriented programming language. C# was designed
to be a somewhat higher-level component-oriented language. The move to a managed environment represents a
sea change in the way you think about programming. C# is about letting go of precise control, and letting the
framework help you focus on the big picture.

With the managed environment of .NET, you give up that level of control. When you choose the type of your
object, the choice of where the object will be created is implicit. Simple types (int, double, and long) are always
created on the stack (unless they are contained within other objects), and classes are always created on the heap.
You cannot control where on the heap an object is created, you can't get its address, and you can't pin it down in
a particular memory location. (There are ways around these restrictions, but they take you out of the
mainstream.)

The very structure of C# reflects the underlying framework. There are no multiple inheritances and there are no
templates because multiple inheritances are terribly difficult to implement efficiently in a managed, garbage-
collected environment, and because generics have not been implemented in the framework.

Compile Target

C++ code usually compiles to assembly language. C# by contrast compiles to Intermediate language (IL),
which has some similarities to java byte code. The IL is subsequently converted to native executable code by a
process of Just-In-Time compilation. The emitted IL code is stored in a file or a set of files known as an
assembly. An assembly essentially forms the unit, in which IL code id packaged, corresponding to a DLL, or
executable file that would be created by C++ compiler.

Memory Management

C# is designed to free the developers from the task of doing memory management. It means in C# you do not
have to explicitly delete memory that was allocated dynamically on the heap, as you could in C++. Rather, the
garbage collector periodically cleans up memory that is no longer needed.
Lets have two C++ variable declarations

int j = 30;
Myclass *pMine=new Myclass

Here the contents of j are stored on the stack. This is exactly that exists with C# value types. Our Myclass
instance is, however stored on the heap, and the pointer to it is on the stack. This is basically the situation with
C# reference type, except that in C# the syntax dresses the pointer up as a reference. The equivalent of C# is:

Int j=30;
Myclass mine=new Myclass()

This code has pretty much the same effect in terms of where the objects are stored as does the above C++ code -
the difference is that Myclass is syntactically treated as a reference rather then a pointer.

The big difference between C++ and C# is that C# doesn't allow you to choose how to allocate memory for a
particular instance. For example, in C++ you wished to do this:

Int* pj=new int(30);
Myclass Mine;dfd

This will cause the int to be allocated on the heap, and the Myclass instance to be allocated on the stack. You
can't do this in C# because C# deems that an int is a value type while any class is always a reference type.

The other difference is that there is no equivalent to C++ delete operator in C#. Instead, with C#, the .Net
garbage collector periodically comes in and scans through the refrences in your code in order to identify which
areas of the heap are currently in use by our program. It is then automatically able to remove all the objects that
are no longer in use. This technique effectively saves you from having to free up nay memory yourself on the
heap.


Program Flow

Program flow is similar in C# to C++. In particular, the following statements works exactly the same way as
they do in C++ and have the same syntax :
For, Return, Goto, Break, Continue
New in C# : for each

(1) If Else Condition

If statement works exactly the same way and has exactly the same syntax in C# as in C++, apart from one point.
The condition in each if and else clause must evaluate to a bool. For example, assuming x is an integer data
types, not a bool, the following C++ code would generate a compilation error in C#.

if(x)
{ }
The correct syntax in C#
If(x != 0)
{ }

This shows that how additionally type safety in C# traps error early.
While and do While

Int x;
While(x) //wrong
While(x != 0) //OK

Just as for if, these statements have exactly syntax and purpose in C# as they do in C++, except that the
condition expression must evaluate to a bool.

(2) Switch

The switch statement serve the same purposes in C# as it does in C++. It is however; more powerful in C#
since you can use a string as the test variables, something that is not possible in C++.

In C# a switch statement may not "fall through" to the next statement if it does any work. Thus, while the
following is legal in C++, it is not legal in C#:

switch (i)
{
case 4:
CallFuncOne();
case 5: // error, no fall through
CallSomeFunc();
}
To accomplish this, you need to use an explicit goto statement:

switch (i)
{
case 4:CallFuncOne();
goto case 5;
case 5:
CallSomeFunc();}

If the case statement does not work (has no code within it) then you can fall

switch (i)
{
case 4: // fall through
case 5: // fall through
case 6:
CallSomeFunc();
}

(3) New control flow statement- for each

C# provides an additional flow control statement, for each. For each loops across all items in array or collection
without requiring explicit specification of the indices.
Syntax:

Foreach(double someElement in MyArray)
{
Console.WriteLine(someElement);
}

(4) Boxing

In some cases you might wish to treat a value type as if it was a reference type. This is achieved by a process
know as boxing.
Syntactically this just means casting the variable to an object.

Int j = 10;
Object boxobj = (object) j;

Boxing acts like any other cast, but you should be aware that it means the contents of the variables will be
copies to the heap and a reference created.
The usual reason for boxing a value in order to pass it to a method that expects a reference type as a parameter.
You can also unbox value, simply by casting it back to its original type.

Int j = 10;
Object boxobj = (object) j;
Int k = (int) boxobj;


The process of unboxing will raise an exception if you attempt to cast to the wrong type and no cast is available
for you to do the conversion.

(5) Structs

Structs are significantly different in C#. In C++ a struct is exactly like a class, except that the default
inheritance and default access are public rather than private.

In C# structs are very different from classes. Structs in C# are designed to encapsulate lightweight objects.
They are value types (not reference types), so they're passed by value. In addition, they have limitations that do
not apply to classes. For example, they are sealed, which means they cannot be derived from or have any base
class other than System.ValueType, which is derived from Object. Structs cannot declare a default (parameter
less) constructor.

(6) Value Types and reference types

C# distinguishes between value types and reference types. Simple types (int, long, double, and so on) and
structs are value types, while all classes are reference types, as are Objects. Value types hold their value on the
stack, like variables in C++, unless they are embedded within a reference type. Reference type variables sit on
the stack, but they hold the address of an object on the heap, much like pointers in C++. Value types are passed
to methods by value (a copy is made), while reference types are effectively passed by reference.

(7) Classes

Classes in C# follow much the same principles as in C++, though there are a few differences in both features
and syntax.

Class MyClass : MyBaseClass
{
Private string SomeFiels;
Public in SomeMethod()
{
Return;
}

Classes defined in C# using what at first sight looks like much the same syntax as in C++, but there are
numerous differences:

There is no access modifier on the name of the base class. Inheritance is always public.

A class can only be derived from one base class. If no base class is explicitly specified, then the class will
automatically be derived from System.Object, which will give the class all the functionality of System.Object,
the most commnly used of which is ToString().

In C++, the only types of class members are variables, functions, constructors, destructors and operator
overloads, C# also permits delegates, events and properties.

The access modifiers public, private and protected have the same meaning as in C++ but there are two
additional access modifiers available:
i. Internal
ii. Protected internal

C++ requires a semicolon after the closing brace at the end of a class definition. This is not required in C#.

(8) Destructors

C# implements a very different programming model for destructors to C++. This is because the garbage
collection mechanism in C# implies that:
There is less need for destructors, since dynamically allocated memory will get removed automatically.

Since it is not possible to predict when the garbage collector will actually destroy a given object, if you do
supply a destructor for a class, it is not possible to predict precisely when that destructor will be executed.
Because memory is cleaned up behind the scenes of C#, you will find that only a small proportion of your
classes actually require destructors. C# has two-stage destruction mechanism:
The class should derive from IDisposable interface and implements Dispose () method.

The class should separately implements at destructor, which is viewed as a reserve mechanism in case a client
doesn't need to call Dispose()
C# destructor looks, syntactically much like a C++ destructor, but it is totally
different. The C# destructor is simply a shortcut for declaring a Finalize method that chain up to its base class.
Thus writing

~MyClass()
{
// do work here
}
is identical to writing
MyClass.Finalize()
{
// do work here
base.Finalize();
}

(9) Virtual methods must be explicitly overridden

In C# the programmer's decision to override a virtual method must be made explicit with the override keyword.

To see why this is useful, assume that a Window class is written by Company A, and that List Box and Radio
Button classes were written by programmers from Company B using a purchased copy of the Company A
Window class as a base. The programmers in Company B have little or no control over the design of the
Window class, including future changes that Company A might choose to make. Now suppose that one of the
programmers for Company B decides to add a Sort method to ListBox:

public class ListBox : Window
{
public virtual void Sort(){"}
}

This presents no problems until Company A, the author of Window, releases version 2 of its Window class. It
turns out that the programmers in Company A also added a Sort method public class Window:

public class Window
{
// "
public virtual void Sort() {"}
}

In C++ the new virtual Sort method in Windows would now act as a base method for the virtual Sort method in
ListBox. The compiler would call the Sort method in ListBox when you intend to call the Sort in Window. In
C# a virtual function is always considered to be the root of virtual dispatch, that is, once C# finds a virtual
method, it looks no further up the inheritance hierarchy If a new virtual Sort function is introduced into Window
the run-time behavior of ListBox is unchanged. When ListBox is compiled again, however, the compiler
generates a warning:

"\class1.cs(54,24): warning CS0114: 'ListBox.Sort()' hides inherited member 'Window.Sort()'.

To make the current member override that implementation, add the override keyword. Otherwise add the new
keyword.

To remove the warning, the programmer must indicate what he intends. He can mark the ListBox Sort method
new, to indicate that it is not an override of the virtual method in Window:

public class ListBox : Window
{
public new virtual void Sort(){"}
}

This action removes the warning. If, on the other hand, the programmer does want to override the method in
Window, he need only use the override keyword to make that intention explicit.

(10) C# requires definite assignment

C# requires definite assignment, which means that the local variables, age, ID, and yearsServed must be
initialized before you call GetStats. This is unnecessarily cumbersome; you're just using them to get values out
of GetStats. To address this problem, C# also provides the out keyword, which indicates that you may pass in
uninitialized variables and they will be passed by reference. This is a way of stating your intentions explicitly:

public class MyClass
{
public void GetStats(out int age, out int ID, out int yearsServed) { }
}

Again, the calling method must match.

MyClass.GetStats(out age,out ID, out yearsServed);

(11) Boolean Values Conversion

There is no conversion between the bool type and other types (specifically int).

C# Boolean values can not be treated as integer If you write a code like this

if(BoolReturnFunction()) {}

and check if it returns zero it will evaluate false and otherwise true

However using assignment versus equality is not allowed ,if you write:

if( x = 4 ) {}

Where x is Boolean type variable, it will give you an compile error
Constant value '4' cannot be converted to a 'bool'

If you write like this:

if(Convert.ToInt32(x)=4) {}

it will give you compilation error
Cannot implicitly convert type 'int' to 'bool'

(12) Exceptions

Exceptions are used in the same way in C# as in C++, apart from the following two differences:

C# defines the finally block, which contains code that is always executed at the end of try block irrespective of
whether any exception was thrown. The lack of this feature in C++ has been a common cause of complaint
among C++ developers. The finally block is executed as soon as control leaves a catch or try block, and
typically contains cleanup code for resources allocated in the try block.

In C++, the class thrown in the exception may be any class. C#, however, requires that the exception be a class
derived from System.Exception.

C++ syntax for catch:

Catch () {}

C# syntax for catch:

Catch { }

The full syntax fro try..catch..finally in C# looks like this

Try {}
Catch (MyException e) {}
Finally {}


(13) Delegates- Substitute of Pointer

C# does not support function pointers. However a similar effect is achieved by wrapping references to methods
in special forms of class know as delegates.
A delegate is a class that can hold a reference to a method. Unlike other classes, a delegate class has a signature,
and it can hold references only to methods that match its signature. A delegate is thus equivalent to a type-safe
function pointer or a callback.

Delegates can be passed around between methods, and used to call the methods to which they contains
reference, in the same way that function pointers can be in C++. Conceptually delegates can be used in a similar
way to an interface with a single method. The main practical difference is that with an interface the method
name is fixed, whereas with a delegate only the signature is fixed - the method name can be different

// delegate declaration
delegate void MyDelegate(int i);
class Program
{
public static void Main()
{
TakesADelegate(new MyDelegate(DelegateFunction));
}
public static void TakesADelegate(MyDelegate SomeFunction)
{
SomeFunction(21);
}
public static void DelegateFunction(int i)
{
System.Console.WriteLine("Called by delegate with number: {0}.", i)
}
}

Output: Called by delegate with number: 21.


(14) Properties

Most C++ programmers try to keep member variables private. This data hiding promotes encapsulation and
allows you to change your implementation of the class without breaking the interface your clients rely on. You
typically want to allow the client to get and possibly set the value of these members, however, so C++
programmers create accessor methods whose job is to modify the value of the private member variables.

In C#, properties are first-class members of classes. To the client, a property looks like a member variable, but
to the implementer of the class it looks like a method. This arrangement is perfect; it allows you total
encapsulation and data hiding while giving your clients easy access to the members.

Properties are defined with property declarations. The first part of a property declaration resembles a field
declaration. The second part includes a Get accessor and/or a Set accessor. In the example below, a class
Employee defines a property Age.

public class Employee
{
private static int age;
public int Age
{
get (return age);
set (age= value);
}
}

(15) Attributes and Metadata.

One significant difference between C# and C++ is that C# provides inherent support for metadata: data about
your classes, objects, methods, and so forth. Attributes come in two flavors: those that are supplied as part of
the CLR and attribute you create for your own purposes. CLR attributes are used to support serialization,
marshaling, and COM interoperability. A search of the CLR reveals a great many attributes. As you've seen,
some attributes are applied to an assembly, others to a class or interface. These are called the attribute targets.

Attributes are applied to their target by placing them in square brackets immediately before the target item.
Attributes may be combined, either by stacking one on top of another.

[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile(".\\keyFile.snk")]

or by separating the attributes with commas.

[assembly: AssemblyDelaySign(false),assembly: AssemblyKeyFile (".\\keyFile.snk")]
Custom Attributes - Custom attributes are user-defined attributes that provide additional information about
program elements. For example, you might define a custom security attribute that specifies the permissions
required by the caller to execute a procedure.

[AttributeUsage(AttributeTargets.All)]
public class DeveloperAttribute : System.Attribute
{
private string name;
public DeveloperAttribute(string name)
{
this.name = name;
}
public virtual string Name
{
get (return name);
}
}






Start Visual C# Express (introduced in the last chapter), and select File -> New project From the project
dialog, select the Console application. This is the most basic application type on a Windows system, but don't
worry, we won't stay here for long. Once you click Ok, Visual C# Express creates a new project for you,
including a file called Program.cs. This is where all the fun is, and it should look something like this:
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
}
}
}
Actually, all these lines doesn't really accomplish anything, or at least it may seem so. Try running the
application by pushing F5 on your keyboard. This will make Visual C# Express compile and execute your code,
but as you will see, it doesn't do much. You will likely just see a black window launch and close again. That is
because our application doesn't do anything yet. In the next chapter we will go through these lines to see what
they are all about, but for now, we really would like to see some results, so let's pretend that we know all about
C# and add a couple of lines to get some output. Within the last set of { }, add these lines:
Console.WriteLine("Hello, world!");
Console.ReadLine();
The code of your first application should now look like this:
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, world!");
Console.ReadLine();
}
}
}
Once again, hit F5 to run it, and you will see the black window actually staying, and even displaying our
greeting to the world. Okay, so we added two lines of code, but what to they do? One of the nice things about
C# and the .NET framework is the fact that a lot of the code makes sense even to the untrained eye, which this
example shows.



The first line uses the Console class to output a line of text, and the second one reads a line of text from the
console. Read? Why? Actually this is a bit of a trick, since without it, the application would just end and close
the window with the output before anyone could see it.

The ReadLine command tells the application to wait for input from the user, and as you will notice, the console
window now allows you to enter text. Press Enter to close it. Congratulations, you have just created your first
C# application! Read on in the next chapter for even more information about what's actually going on.



To see some actual progress, we didn't go into much detail about the lines of code we used, so this chapter is an
explanation of the Hello world example code. As you can probably see from the code, some of the lines look
similar, so we will bring them back in groups for an individual explanation. Let's start with the shortest and
most common characters in our code: The { and }. They are often referred to as curly braces, and in C#, they
mark the beginning and end of a logical block of code. The curly braces are used in lots of other languages,
including C++, Java, JavaScript and many others. As you can see in the code, they are used to wrap several
lines of code which belongs together. In later examples, it will be clearer how they are used.

Now let's start from the beginning:
using System;
using System.Collections.Generic;
using System.Text;
using is a keyword, highlighted with blue by the editor. The using keyword imports a namespace, and a
namespace is a collection of classes. Classes brings us some sort of functionality, and when working with an
advanced IDE like Visual C# Express, it will usually create parts of the trivial code for us. In this case, it
created a class for us, and imported the namespaces which is required or expected to be used commonly. In this
case, 3 namespaces are imported for us, each containing lots of useful classes. For instance, we use the Console
class, which is a part of the System namespace.

As you can see, we even get our own namespace:
namespace ConsoleApplication1
The namespace ConsoleApplication1 is now the main namespace for this application, and new classes will be a
part of it by default. Obviously, you can change this, and create classes in another namespace. In that case, you
will have to import this new namespace to use it in your application, with the using statement, like any other
namespace.

Next, we define our class. Since C# is truly an Object Oriented language, every line of code that actually does
something, is wrapped inside a class. In the case, the class is simply called Program:
class Program
We can have more classes, even in the same file. For now, we only need one class. A class can contain several
variables, properties and methods, concepts we will go deeper into later on. For now, all you need to know is
that our current class only contains one method and nothing else. It's declared like this:
static void Main(string[] args)
This line is probably the most complicated one in this example, so let's split it up a bit. The first word is static.
The static keyword tells us that this method should be accesible without instantiating the class, but more about
this in our chapter about classes.

The next keyword is void, and tells us what this method should return. For instance, int could be an integer or a
string of text, but in this case, we don't want our method to return anything, or void, which is the same as no
type.

The next word is Main, which is simply the name of our method. This method is the so-called entry-point of
our application, that is, the first piece of code to be executed, and in our example, the only piece to be executed.
now, after the name of a method, a set of arguments can be specified within a set of parentheses. In our
example, our method takes only one argument, called args. The type of the argument is a string, or to be more
precise, an array of strings, but more on that later. If you think about it, this makes perfect sense, since
Windows applications can always be called with an optinal set of arguments. These arguments will be passed as
text strings to our main method.

And that's it. You should now have a basic understanding of our first C# application, as well as the basic
principles of what makes a console application work.


Data types
In C#, variables are categorized into the following types:
Value types
Reference types
Pointer types
Value Types
Value type variables can be assigned a value directly. They are derived from the class System.ValueType.
The value types directly contain data. Some examples are int, char, float, which stores numbers, alphabets,
floating point numbers, respectively. When you declare an int type, the system allocates memory to store the
value.
The following table lists the available value types in C# 2010:
Type Represents Range
Default
Value
bool Boolean value True or False False
byte 8-bit unsigned integer 0 to 255 0
char 16-bit Unicode character U +0000 to U +ffff '\0'
decimal
128-bit precise decimal values with
28-29 significant digits
(-7.9 x 10
28
to 7.9 x 10
28
) / 10
0 to 28
0.0M
double
64-bit double-precision floating point
type
(+/-)5.0 x 10
-324
to (+/-)1.7 x 10
308
0.0D
float
32-bit single-precision floating point
type
-3.4 x 10
38
to + 3.4 x 10
38
0.0F
int 32-bit signed integer type -2,147,483,648 to 2,147,483,647 0
long 64-bit signed integer type
-923,372,036,854,775,808 to
9,223,372,036,854,775,807
0L
sbyte 8-bit signed integer type -128 to 127 0
short 16-bit signed integer type -32,768 to 32,767 0
uint 32-bit unsigned integer type 0 to 4,294,967,295 0
ulong 64-bit unsigned integer type 0 to 18,446,744,073,709,551,615 0
ushort 16-bit unsigned integer type 0 to 65,535 0
To get the exact size of a type or a variable on a particular platform, you can use the sizeof method. The
expression sizeof(type) yields the storage size of the object or type in bytes. Following is an example to get the
size of int type on any machine:
namespace DataTypeApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Size of int: {0}", sizeof(int));
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Size of int: 4
Reference Types
The reference types do not contain the actual data stored in a variable, but they contain a reference to the
variables.
In other words, they refer to a memory location. Using more than one variable, the reference types can refer to a
memory location. If the data in the memory location is changed by one of the variables, the other variable
automatically reflects this change in value. Example of built-in reference types are: object, dynamic and
string.
Object Type
The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). Object is an
alias for System.Object class. So object types can be assigned values of any other types, value types, reference
types, predefined or user-defined types. However, before assigning values, it needs type conversion.
When a value type is converted to object type, it is called boxing and on the other hand, when an object type is
converted to a value type, it is called unboxing.
object obj;
obj = 100; // this is boxing
Dynamic Type
You can store any type of value in the dynamic data type variable. Type checking for these types of variables
takes place at run-time.
Syntax for declaring a dynamic type is:
dynamic <variable_name> = value;
For example,
dynamic d = 20;
Dynamic types are similar to object types except that type checking for object type variables takes place at
compile time, whereas that for the dynamic type variables take place at run time.
String Type
The String Type allows you to assign any string values to a variable. The string type is an alias for the
System.String class. It is derived from object type. The value for a string type can be assigned using string
literals in two forms: quoted and @quoted.
For example,
String str = "Tutorials Point";
A @quoted string literal looks like:
@"Tutorials Point";
The user-defined reference types are: class, interface, or delegate. We will discuss these types in later chapter.
Pointer Types
Pointer type variables store the memory address of another type. Pointers in C# have the same capabilities as in
C or C++.
Syntax for declaring a pointer type is:
type* identifier;
For example,
char* cptr;
int* iptr;







C# - Variables
Advertisements

Previous Page
Next Page

A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C#
has a specific type, which determines the size and layout of the variable's memory; the range of values that can
be stored within that memory; and the set of operations that can be applied to the variable.
We have already discussed various data types. The basic value types provided in C# can be categorized as:
Type Example
Integral types sbyte, byte, short, ushort, int, uint, long, ulong and char
Floating point types float and double
Decimal types decimal
Boolean types true or false values, as assigned
Nullable types Nullable data types
C# also allows defining other value types of variable like enum and reference types of variables like class,
which we will cover in subsequent chapters. For this chapter, let us study only basic variable types.
Variable Definition in C#
Syntax for variable definition in C# is:
<data_type> <variable_list>;
Here, data_type must be a valid C# data type including char, int, float, double, or any user-defined data type,
etc., and variable_list may consist of one or more identifier names separated by commas.
Some valid variable definitions are shown here:
int i, j, k;
char c, ch;
float f, salary;
double d;
You can initialize a variable at the time of definition as:
int i = 100;
Variable Initialization in C#
Variables are initialized (assigned a value) with an equal sign followed by a constant expression. The general
form of initialization is:
variable_name = value;
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal
sign followed by a constant expression as:
<data_type> <variable_name> = value;
Some examples are:
int d = 3, f = 5; /* initializing d and f. */
byte z = 22; /* initializes z. */
double pi = 3.14159; /* declares an approximation of pi. */
char x = 'x'; /* the variable x has the value 'x'. */
It is a good programming practice to initialize variables properly, otherwise sometimes program would produce
unexpected result.
Try the following example which makes use of various types of variables:
namespace VariableDefinition
{
class Program
{
static void Main(string[] args)
{
short a;
int b ;
double c;

/* actual initialization */
a = 10;
b = 20;
c = a + b;
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
a = 10, b = 20, c = 30
Accepting Values from User
The Console class in the System namespace provides a function ReadLine() for accepting input from the user
and store it into a variable.
For example,
int num;
num = Convert.ToInt32(Console.ReadLine());
The function Convert.ToInt32() converts the data entered by the user to int data type, because
Console.ReadLine() accepts the data in string format.
Lvalues and Rvalues in C#:
There are two kinds of expressions in C#:
1. lvalue: An expression that is an lvalue may appear as either the left-hand or right-hand side of an
assignment.
2. rvalue: An expression that is an rvalue may appear on the right- but not left-hand side of an assignment.
Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and
so may not be assigned and can not appear on the left-hand side. Following is a valid statement:
int g = 20;
But following is not a valid statement and would generate compile-time error:
10 = 20;


C# - Constants and Literals
Advertisements

Previous Page
Next Page

The constants refer to fixed values that the program may not alter during its execution. These fixed values are
also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a
character constant, or a string literal. There are also enumeration constants as well.
The constants are treated just like regular variables except that their values cannot be modified after their
definition.
Integer Literals
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or
0X for hexadecimal, 0 for octal, and no prefix id required for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively.
The suffix can be uppercase or lowercase and can be in any order.
Here are some examples of integer literals:
212 /* Legal */
215u /* Legal */
0xFeeL /* Legal */
078 /* Illegal: 8 is not an octal digit */
032UU /* Illegal: cannot repeat a suffix */
Following are other examples of various types of Integer literals:
85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */
Floating-point Literals
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can
represent floating point literals either in decimal form or exponential form.
Here are some examples of floating-point literals:
3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */
While representing using decimal form, you must include the decimal point, the exponent, or both and while
representing using exponential form you must include the integer part, the fractional part, or both. The signed
exponent is introduced by e or E.
Character Constants
Character literals are enclosed in single quotes, e.g., 'x' and can be stored in a simple variable of char type. A
character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character (e.g.,
'\u02C0').
There are certain characters in C# when they are preceded by a backslash they will have special meaning and
they are used to represent like newline (\n) or tab (\t). Here, you have a list of some of such escape sequence
codes:
Escape sequence Meaning
\\ \ character
\' ' character
\" " character
\? ? character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\ooo Octal number of one to three digits
\xhh . . . Hexadecimal number of one or more digits
Following is the example to show few escape sequence characters:
namespace EscapeChar
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello\tWorld\n\n");
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Hello World
String Literals
String literals or constants are enclosed in double quotes "" or with @"". A string contains characters that are
similar to character literals: plain characters, escape sequences, and universal characters.
You can break a long line into multiple lines using string literals and separating the parts using whitespaces.
Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"
"hello, \
dear"
"hello, " "d" "ear"
@"hello dear"
Defining Constants
Constants are defined using the const keyword. Syntax for defining a constant is:
const <data_type> <constant_name> = value;
The following program demonstrates defining and using a constant in your program:
using System;

namespace DeclaringConstants
{
class Program
{
static void Main(string[] args)
{
const double pi = 3.14159; // constant declaration
double r;
Console.WriteLine("Enter Radius: ");
r = Convert.ToDouble(Console.ReadLine());
double areaCircle = pi * r * r;
Console.WriteLine("Radius: {0}, Area: {1}", r, areaCircle);
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Enter Radius:
3
Radius: 3, Area: 28.27431

You might also like