2007/12/12

C# Introduction and Overview , Variables are type-safe , Expressiveness, and Flexibility ,Beginners

C# Introduction and Overview

For the past two decades, C and C++ have been the most widely used languages for developing commercial and business software. While both languages provide the programmer with a tremendous amount of fine-grained control, this flexibility comes at a cost to productivity. Compared with a language such as Microsoft® Visual Basic®, equivalent C and C++ applications often take longer to develop. Due to the complexity and long cycle times associated with these languages, many C and C++ programmers have been searching for a language offering better balance between power and productivity.

There are languages today that raise productivity by sacrificing the flexibility that C and C++ programmers often require. Such solutions constrain the developer too much (for example, by omitting a mechanism for low-level code control) and provide least-common-denominator capabilities. They don't easily interoperate with preexisting systems, and they don't always mesh well with current Web programming practices.

The ideal solution for C and C++ programmers would be rapid development combined with the power to access all the functionality of the underlying platform. They want an environment that is completely in sync with emerging Web standards and one that provides easy integration with existing applications. Additionally, C and C++ developers would like the ability to code at a low level when and if the need arises.Microsoft Introduces C#

The Microsoft solution to this problem is a language called C# (pronounced "C sharp"). C# is a modern, object-oriented language that enables programmers to quickly build a wide range of applications for the new Microsoft .NET platform, which provides tools and services that fully exploit both computing and communications.

Because of its elegant object-oriented design, C# is a great choice for architecting a wide range of components-from high-level business objects to system-level applications. Using simple C# language constructs, these components can be converted into XML Web services, allowing them to be invoked across the Internet, from any language running on any operating system.
More than anything else, C# is designed to bring rapid development to the C++ programmer without sacrificing the power and control that have been a hallmark of C and C++. Because of this heritage, C# has a high degree of fidelity with C and C++. Developers familiar with these languages can quickly become productive in C#.Productivity and Safety
The new Web economy-where competitors are just one click away-is forcing businesses to respond to competitive threats faster than ever before. Developers are called upon to shorten cycle times and produce more incremental revisions of a program, rather than a single monumental version.

C# is designed with these considerations in mind. The language is designed to help developers do more with fewer lines of code and fewer opportunities for error.
Embraces emerging Web programming standardsThe new model for developing applications means more and more solutions require the use of emerging Web standards like Hypertext Markup Language (HTML), Extensible Markup Language (XML), and Simple Object Access Protocol (SOAP). Existing development tools were developed before the Internet or when the Web as we know it today was in its infancy. As a result, they don't always provide the best fit for working with new Web technologies.

C# programmers can leverage an extensive framework for building applications on the Microsoft .NET platform. C# includes built-in support to turn any component into an XML Web service that can be invoked over the Internet-from any application running on any platform.
Even better, the XML Web services framework can make existing XML Web services look just like native C# objects to the programmer, thus allowing developers to leverage existing XML Web services with the object-oriented programming skills they already have.
There are more subtle features that make C# a great Internet programming tool. For instance, XML is emerging as the standard way to pass structured data across the Internet. Such data sets are often very small. For improved performance, C# allows the XML data to be mapped directly into a struct data type instead of a class. This is a more efficient way to handle small amounts of data.

Eliminates costly programming errorsEven expert C++ programmers can make the simplest of mistakes-forgetting to initialize a variable, for instance-and often those simple mistakes result in unpredictable problems that can remain undiscovered for long periods of time. Once a program is in production use, it can be very costly to fix even the simplest programming errors.
The modern design of C# eliminates the most common C++ programming errors. For example:
Garbage collection relieves the programmer of the burden of manual memory management.
Variables in C# are automatically initialized by the environment.

Variables are type-safe.

The end result is a language that makes it far easier for developers to write and maintain programs that solve complex business problems.

Reduces ongoing development costs with built-in support for versioningUpdating software components is an error-prone task. Revisions made to the code can unintentionally change the semantics of an existing program. To assist the developer with this problem, C# includes versioning support in the language. For example, method overriding must be explicit; it cannot happen inadvertently as in C++ or Java. This helps prevent coding errors and preserve versioning flexibility. A related feature is the native support for interfaces and interface inheritance. These features enable complex frameworks to be developed and evolved over time.
Put together, these features make the process of developing later versions of a project more robust and thus reduce overall development costs for the successive versions.Power,

Expressiveness, and Flexibility

Better mapping between business process and implementationWith the high level of effort that corporations spend on business planning, it is imperative to have a close connection between the abstract business process and the actual software implementation. But most language tools don't have an easy way to link business logic with code. For instance, developers probably use code comments today to identify which classes make up a particular abstract business object.
The C# language allows for typed, extensible metadata that can be applied to any object. A project architect can define domain-specific attributes and apply them to any language element-classes, interfaces, and so on. The developer then can programmatically examine the attributes on each element. This makes it easy, for example, to write an automated tool that will ensure that each class or interface is correctly identified as part of a particular abstract business object, or simply to create reports based on the domain-specific attributes of an object. The tight coupling between the custom metadata and the program code helps strengthen the connection between the intended program behavior and the actual implementation.
Extensive interoperabilityThe managed, type-safe environment is appropriate for most enterprise applications. But real-world experience shows that some applications continue to require "native" code, either for performance reasons or to interoperate with existing application programming interfaces (APIs). Such scenarios may force developers to use C++ even when they would prefer to use a more productive development environment.
C# addresses these problems by:

Including native support for the Component Object Model (COM) and Windows.-based APIs.
Allowing restricted use of native pointers.

With C#, every object is automatically a COM object. Developers no longer have to explicitly implement IUnknown and other COM interfaces. Instead, those features are built in. Similarly, C# programs can natively use existing COM objects, no matter what language was used to author them.

For those developers who require it, C# includes a special feature that enables a program to call out to any native API. Inside a specially marked code block, developers are allowed to use pointers and traditional C/C++ features such as manually managed memory and pointer arithmetic. This is a huge advantage over other environments. It means that C# programmers can build on their existing C and C++ code base, rather than discard it.
In both cases-COM support and native API access-the goal is to provide the developer with essential power and control without having to leave the C# environment.Conclusion
C# is a modern, object-oriented language that enables programmers to quickly and easily build solutions for the Microsoft .NET platform. The framework provided allows C# components to become XML Web services that are available across the Internet, from any application running on any platform.

The language enhances developer productivity while serving to eliminate programming errors that can lead to increased development costs. C# brings rapid Web development to the C and C++ programmer while maintaining the power and flexibility that those developers call for.

First tutorial

You should first open a DOS command shell. (If you don't know what it is, clic on the Start menu then run (at the bottom) and type, in the text field: "cmd".exercise: there is an easiest way to do that, try to find it.) You should begin to work in an empty directory for this. let call it "C:\learncs". Type in the shell: > md C:\learncs
> cd C:\learncs
> C:
Now you should create your first C# program, type "notepad hello.cs" and type (in the notepad) using System;

public class Hello
{
public static void Main()
{
Console.WriteLine("Hello C# World :-)");
}
}
the using keyword just let you write Console at line 7, instead of System.Console. It's very usefull shortcut when you use a lot of "class" define in System.Save the file.Now you could compile. Type in the DOS Shell again and type: csc /nologo /out:hello.exe hello.csYou probaly have some errors, correct them, compile again, and now you have a working hello.exe program... type hello, see...
Second tutorial Congratulation you've done the most difficult, let increase the difficulty. and create an object instance. in the DOS shell create a new directory: > md ..\learncs2
> cd ..\learncs2
> notepad hello.cs
and then type, in the notepad using System;

public class Echo
{
string myString;

public Echo(string aString)
{
myString = aString;
}

public void Tell()
{
Console.WriteLine(myString);
}
}

public class Hello
{
public static void Main()
{
Echo h = new Echo("Hello my 1st C# object !");
h.Tell();
}
}
Wouah, 25 lines! That's a program! Save it, compile it, run it...What happened? csc look for a Main() function in your program, it should find one (and only one) and it will be the entry point of your program.In this tutorial we create 2 classes: Echo & Hello. In the Main() method you create an Echo object (an instance of the Echo class) with the keyword newThen we called the instance method "Tell()".the upper case letter on class or Method is just a MS convention, do as it pleased you.public is a visibility access, method wich are not public could not be seen from outside, there is also other visibility keywords, to learn more, clic on Start menu-> Programs -> Microsoft .NET Framework SDK -> Documentation there is a search window, an index window, etc... try to learn more about public private protected.
Third tutorialNow you become to be pretty confident, I guess, so we could start using multiple file, and even a dll ? go into an other directory (or stay in this one, I won't mind) and create 2 file:hello.cs using System;

public class Hello
{
public static void Main()
{
HelloUtil.Echo h = new HelloUtil.Echo("Hello my 1st C# object !");
h.Tell();
}
}
echo.cs using System;

namespace HelloUtil
{
public class Echo
{
string myString;

public Echo(string aString)
{
myString = aString;
}

public void Tell()
{
Console.WriteLine(myString);
}
}
}
Note in hello.cs I have used the syntax "HelloUtil.Echo" it's because Echo is in the namespace HelloUtil, you could have typed (at he start of the file) using HelloUtil and avoid HelloUtil., that's the way namespace work.
Now you could compile both in one .exe with > csc /nologo /out:hello.exe *.csBut it's not my intention, no.Well.(Have you tried?)Let's go building a DLL: > csc /nologo /t:library /out:echo.dll echo.csthat's it (dir will confirm).Now we could use it ... > csc /out:hello.exe /r:echo.dll hello.cs if you typed "hello" it will worked as usual..., but if you delete "echo.dll" the program will now crash: it use the DLL. You could also change Echo.cs, rebuild the DLL and see... that's the advantage of DLL!
You could also put your DLL in the global assembly cache (GAC), and any program would be able to access it, even if the DLL is not in its directory! to put it in the GAC, I sugest you read MS doc but here are the unexplained step:
create your assembly key, create it once and use it for every version. you create it with: sn -k myKeyName.snkthe .snk file should be in your compilation directory (the one where your run csc)
create a strong asssembly title by adding in any .cs source file the following directive at top level: using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle("My Lib Title")]
[assembly: AssemblyVersion("1.2.3.4")]
[assembly: AssemblyKeyFile("myKeyName.snk")]

now add it to the GAC: > gacutil.exe /if myLib.dll
By the way, did I tell you ? when I referenced the hello.dll while compiling, remember? csc /out:hello.exe /r:echo.dll hello.cs, it could have been any assembly, even a .exe !!!
Fourth tutorial Congratulation you would soon be able to hack CsGl but there is one last step you should understand : interop (with C code).You will need a C compiler, I advise gcc for windows called , it's free, it's good, it's GCC!We will create 3 file:echo.c #include

#define DLLOBJECT __declspec(dllexport)

DLLOBJECT void writeln(char* s)
{
printf("%s\n", s);
}
echo.cs using System;
using System.Runtime.InteropServices;

namespace HelloUtil
{
public class Echo
{
[DllImport("echo.native.dll", CallingConvention=CallingConvention.Cdecl)]
static extern void writeln(string s);

string myString;

public Echo(string aString)
{
myString = aString;
}

public void Tell()
{
writeln(myString);
}
}
}
hello.cs using System;
using HelloUtil;

public class Hello
{
public static void Main()
{
Echo h = new Echo("Hello my 1st interop code !");
h.Tell();
}
}

Hehe, here you discover a completly new thing, Attribute."[DllImport(.." is an attribute.You could tag any method/field/class with any number of attribute.They generate extra information that could be used by anyone who could understand them.This DllImport attribute is understand by the compiler and told him that the function below is in fact in a DLL whose name is "echo.native.dll". I add a calling convention parameter as the default .NET calling convention is __stdcall whereas, in C, it's __cdecl.By the way, if you look for DllImport in the documentation, look for DllImportAttribute, because you remove "Attribute" to attribute classname when using them, it's like this.
And now let's compile this! > csc /nologo /t:library /out:echo.dll echo.cs

> csc /nologo /out:hello.exe /r:echo.dll hello.cs
>
> rem "if the following line don't work, read bellow.."
> gcc -shared -o echo.native.dll echo.c
> strip echo.native.dll

the 2 last line (the gcc & strip command) are for building the "C-DLL".If they don't work maybe gcc is not in a directory listed in your path environment variable ? check with: %lt; echo %PATH%Well it's probably not,anyway, so type, assumin mingc is in C:\MinGW: set PATH=C:\MinGW;%PATH%And try again... you sure it's not a syntax error ?If it compile test it now: helloGreat isn't it ?

Now I should admit I didn't tell you all the truth. echo.dll and echo.native.dll are not the same kind of DLL. It's not just the language (C / C#) the C one is a plain executable full of, probably, x86 instruction, whereas the C# one is what MS call a portable executable.. anyway they are different.If you install echo.dll in the GAC it wont work because it won't find echo.native.dll except if you put in into the PATH (like C:\Windows\System32).In the same manner when you add the reference in VS.NET echo.native.dll is overlooked and your program won't work....So either put the native one in your path or copy it in the debug/release directory of VS.NET.Or do everything by hand (makefile? build.bat?) and put all your dll in you build directory, and everything work fine..

No comments: