Sponsored Ad

Friday, October 30, 2009

How C# is different from Java

C# absent in Java

  • C # includes the most primitive types and functionality to detect arithmetic exceptions.
  • Includes a large number of notational conveniences over Java, many of whom, like operator overloading and user-defined sets, already knows the large community of C + + programmers.
  • Event management is a "first-class citizen," is part of the language itself.
  • Allows the definition of "structures" which are similar to classes, but can be allocated on the stack (unlike instances of classes in C # and Java).
  • C # implements properties as part of the language syntax.
  • C # allows switch statements to operate on strings.
  • C # allows anonymous methods providing closure functionality.
  • C # allows iterator that uses co-routines through a functional style yield keyword.
  • C # has support for output parameters, assist in the return of multiple values, a prominent shared by C + + and SQL.
  • C # has the ability to alias namespaces.
  • C # has "Explicit Member Implementation" which allows a class to implement specific methods of an interface, independent of their class methods. This also allows to implement two different interfaces which happen to have a method of the same name. The methods of an interface need not be "public" because they may be made to be accessible only through that interface.
  • C # provides integration with COM.
  • Following the example of C and C + +, C # allows call by reference primitive and reference types.

Java absent in C#

  • Keyword strictfp * Java guarantees the result of floating point operations remain the same on all platforms.
  • Java supports exceptions to better monitor the implementation of error trapping and handling.

Web Enable in C# Program

How can they permit our web application in C #? First they need a web server. You can use IIS (built-in for Windows 2000/NT/XP professionals), or Apache. Apache is the most popular & practical & easy to configure web server available on the Web. It can be downloaded. Apache runs on most operating systems. After installation on the network drive or local drive, you see a quantity of subdirectories from which they can see cgi-bin & htdocs. The subdirectory cgi-bin is used to contain the executable files, while htdocs is used to contain the HTML files. When installing & configuring your installation is correct (to help see the web-site), type the address as & press Enter. They see a default page, placed in the htdocs directory, & view the Apache server jogging!

Change the new htdocs subdirectory. html and create an HTML file to show a form page as follows

Code Snippet
  1. <html>
  2. <form>
  3. <input type=submit value=search>
  4. </form>
  5. </html>

Now save this file! Open your favorite browser and type http://127.0.0.1/new.html and press Enter. We see the results! A button with a text (caption) search, is on page ...... !

Reflection in C#

The ability to find information about objects at runtime is called reflection. In reflection they can know what kind of object, the details of the methods of an object, & even generate a dynamic runtime. Reflection is a powerful mechanism with the Process.Reflection namespace contains classes for forty years & interface. The kind of guy is the root of all reflection operations & the object that represents a type within the process. The type is an abstract base class that allows multiple implementations.

This class is the primary means by which we access metadata and acts as a gateway to the reflection API. Provides methods to get information about a type declaration, such as constructors, methods, fields, properties and events of a class and the module assembly in which the class implements.

Program Entry point in C#

This article will review the entry points into C # programs, and possible errors that can come across. The function to be called in any C # program is Main. We can have up to four ways to declare Main in our program. These are:

Code Snippet
  1. static void Main( ) {...}
  2. static int Main( ) {...}
  3. static void Main(string[ ] a) {...}
  4. static int Main(string[ ] args) {...}

Application Framework with C#

Application Frameworks are generalized and customized, which can form the basis for a software program completely and totally functional. In recent years frameworks have been successfully applied in some specific applications, including user interfaces and data processing. A framework is a breakthrough because it means that developers do not have to start from scratch if a framework of success can generate a user interface, which can generate any user interface.

For example, using Java applets and servlets, we need only replace some of the methods to establish our running code. The programming model and Java Servlets Java Applet based on the Model Framework. Microsoft has also implemented the MFC class libraries in the same pattern.

Prerequisite

I guess the work that the reader must be confident with C #. Apart from that if he / she has basic knowledge of Java Applet and Servlet in order to better understand the basic concept behind this.

Tools

The code is tested. NET Framework version version that runs on Windows 2000. The application does not need a graphical interface that uses a notepad and the command line # C compiler to complete the code.

Socket Programming in C#

About socket programming. In the previous article they created a client but the client used to make blocking IO calls (Get) to read data at regular intervals (by clicking the button Rx). But as I said in my previous article, that the model works well in a real application. Also, since Windows is an event-based process, the application (client) should get notifications whenever any data is received so that the client can read instead of voting for the client continuously the data .
Well, that is possible with a tiny effort. If you read the first part of this article, you already know that the Socket class in the namespace Systems.Net.Sockets has several methods such as receiving and Music, that are blocking calls. In addition there's also functions as BeginReceive, etc. These are for BeginSend E / S asynchronous. For example, there's at least three problems with the reception of locking:

When you call the receive function call blocks if no data is present, the call blocks until some data arrives. Even if data of the calling when reception is not known when to call next time. That has to make choices, which is not an efficient way.

Quick & Dirty .NET Guide to C#/VB OOP

Everyone, I am sure that has helped net more than a reading passage. Must be excited in the power of his frame. People with pure programming skills and prior knowledge of the pre-.NET technologies have been found to be absent on the strength and the methodology of pure object-oriented programming (Object Oriented Programming) and the medium environment or language.

All the newcomers. NET face a new challenge - to adjust their thinking process in programming and undo bad habits that many have gained from working with a non-OOP environment. Developers with prior ASP / VBScript experience certainly fell on these habits simply because it never promoted this kind of practices. So when it comes a. NET can be quite difficult to have to rethink or relearn all "programmed" way of thinking.

What we are trying to achieve in this article is to make all non-OOP programmers up with this whole brave new world of thinking about programming. Make an adjustment for terms such as classes, objects, properties, structures, overloading, inheritance, abstraction and polymorphism may seem inaccessible to non-experienced programmers with OOP insufficient awareness. Therefore, my intention is to cut to the chase with all these methodologies and terms, and show how they fit together.

Although this article will not be a treaty comprehensive Object Oriented Programming, however, your goal is to present a quick and dirty C # / VB Object-Oriented Programming. Moreover, although this article can be slightly more oriented towards C #, VB all major assessments or similarities are addressed and demonstrated. Of course, bear in mind C # is case sensitive. By the way, do not be discouraged by the length of this article, many are simply repeated code examples for both languages.

How to NNTP in C#

This is the article on Internet programming with the new programming language Microsoft C #.

NNTP is a protocol more disappearing into the family of Internet protocols. The protocol used to retrieve news from news server, aka NetNews servers. The protocol works by posting messages on various forums, aka newsgroups. Then, other users can read recent messages in the forums. There are also protocols for distributing NetNews NetNews content across multiple servers, allowing thousands of servers to share news and forums. The most popular news server is, of course, Microsoft. More often than not, you can launch your NetNews client by typing the URL NNTP in the address bar of your browser.

public class NntpException : System.ApplicationException
{
public NntpException(string str)
:base(str)
{
}
};

I'm still unsure how best to implement the kinds of exceptions. NET and as such I have remained true to my roots of C + +. I am researching something else and might consider writing a short article on precisely this subject. Let's see. The next step is the class declaration. I Nntp derived from the class System.Net.Sockets TcpClient class in the namespace of the framework. NET.

public class nntp: System.Net.Sockets.TcpClient
We will inherit a lot of basic functions of the TcpClient class.

Parameter Passing in C#

At. NET (C # and therefore) there's one main types of type: reference types and value types. They act differently, as well as a lot of confusion about parameter passing is right up to people not understanding the difference between them. Here is a brief explanation:
A reference type is a type whose reference value at the appropriate data than the data itself. For example, consider the following code:

StringBuilder sb = new StringBuilder ();

I have used StringBuilder as a random example of a reference type - there is nothing special.) Here, they declare a variable SB, generate a new StringBuilder object, and assign the SB, a reference to the object. The value of SB is not the object itself, reference is. Allocation of participation reference types is simple - the value assigned is the value of the expression / variable - ie the reference. This will be shown in this example:

First = new StringBuilder StringBuilder ();
StringBuilder second = first;

Here they declare a first variable, generate a new StringBuilder object, and assign to first a reference to the object. Then assign the second value of the first. This means that both refer to the same object. They remain, however, the independent variables themselves. Alter the value of the first won't alter the value of the second - but simultaneously their values are still references the same object, changes made to the object through the first variable will be visible through the second variable. Here is a demonstration that:

First = new StringBuilder StringBuilder ();
StringBuilder second = first;
first.Append ( "hello");
first = null;
Console.WriteLine (second);

Here, first declare a variable, generate a new StringBuilder object, and assign to first a reference to the object. Then assign the second value of the first. They then call the Append technique on this object through the reference in the first variable. After this, they set the first variable to null (a value which does not refer to any object). Finally, they show the results of the ToString technique call the StringBuilder object through the reference in the second variable. Hello shown, demonstrating that although the first value has changed, the data within the object that is used to refer to non - and the latter still refers to that object.

Class types, interface types, delegate types and array types are all reference types.

Thursday, October 29, 2009

C# 3.0 Language Features

If you're a C # on today, probably too used to writing classes with basic properties like the snippet below:

public class Person
{

private string _firstName;
private string _lastName;
private int _age;

public string FirstName
{

get
{
return _firstName;
}
set
{
_firstName = value;
}
}

public string LastName
{

get
{
return _lastName;
}
set
{
_lastName = value;
}
}

public int Age
{

get
{
return _age;
}
set
{
_age = value;
}
}
}

Note that we are not actually adding any logic in the getter / setters of our properties - instead just get / set the value directly to a field. This raises the question - why not just use fields instead of properties? Well - there are plenty of negative aspects of the exposure of public fields. Two major problems are: 1) it is easy DataBind against the fields, and 2) if exposed public fields of classes can not be changed later to the properties (for example: to add validation logic for agencies development) without having to recompile assemblies compiled with the class of age.

The new C # compiler that is included in "Orcas" provides an elegant way to make the code more concise while retaining the flexibility of the building with a new language feature called "automatic properties". Automatic properties allow you to avoid having to manually declare a private field and write the get / set logic - instead the compiler can automate creating the private field and default get / set operations for you.

For example, using automatic properties I can now re-write the code above as given below:

public class Person {
public string FirstName {
get; set;
}

public string LastName {
get; set;
}
public int Age {
get; set;
}
}

Or If I want to be really terse, I can collapse the whitespace even further like so:

public class Person {
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}

When the C # "Orcas" compiler encounters an empty get / set property implementation as before, are now automatically generates a private field for you in your class, and implement a public property getter and setter to applying it. The benefit of this is that one type of contract perspective, the class looks exactly like he did with our first application (more details) above. This means that - unlike the public fields - which may in future add validation logic within my property regulator application without having to change any external component that references my class.

Bluffer's Guide to C# 3

Visceral Guide to C # 3.0! This is not meant to give you enough information to be useful to encode - but you can pretend you know what you're talking geek in the right company. More seriously, it will give a very rough to give some context, if you decide to further investigate a particular feature.

Each of the main features of C # 3 is here with:

  • A brief description of the function, usually with an example
  • A pair of "Bluff extra power" to launch a conversation phrases to get bonus points from their listeners - if not more evidence
  • A couple of "call his bluff," says that sound plausible but are actually incorrect. If you feel another person is perhaps exaggerate their experience, see if the ground traps.

Automatic properties

Automatic properties are an easy way to write the properties you just get and set their values directly from / to a variable of support. For example, this code:

string name;
public string Name
{
get { return name; }
set { name = value; }
}

can be written in C# 3 like this:

public string Name { get; set; }

Extra Bluff Power
  • The compiler generates the backing variable always contains angle brackets (<>) for the variable can not legitimately be referred to in the C # code, and never be faced with a handwritten variable.
  • If you use automatic properties in a structure is necessary to include an explicit call to the constructor without parameters for each additional constructor to write.
Call their bluff
  • Automatic Properties is officially called "auto-properties" in the specification. (Fact: They are called out automatically Properties.)
  • Automatic properties are indistinguishable from the properties typically generated manually. (Fact: The compiler adds an attribute CompilerGenerated both the getter and setter.)

Object Initializers allow you to configure the properties of a very simple object at the time of construction. Collection initializers are similar, allowing you to complete a collection. Examples:

// Object initializer
ProcessStartInfo psi = new ProcessStartInfo
{
FileName="Notepad.exe",
Arguments="c:\\autoexec.bat",
UseShellExecute=true
};

// Collection initializer for List
List<string> words = new List<string>
{ "the", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog" };

// Collection initializer for Dictionary
Dictionary<string,int> ages = new Dictionary<string,int>
{
{ "Jon", 31 },
{ "Holly", 32 },
{ "Tom", 4 }
};

Lterator blocks in C# 2: auto-generated state machines

Iterators have been in .NET since its first release, but C# 2 made them easy to implement using iterator blocks. In this editorial I'll go in to details of how the Microsoft C# compiler converts iterator blocks in to state machines. If you are not sure about the IEnumerable & IEnumerator interfaces (& their generic counterparts) or the basics of iterator blocks, it would be worth reading an editorial giving more details about them before continuing with this editorial.Pretty much all of this editorial is implementation-specific. The Mono compiler may approach things in a slightly different way, for instance. It is likely to be similar though; when in doubt as to what you can rely on, consult the language specification.

what's the pattern?

This article originally was because a reader asked about the difference between the use of repeater blocks for methods returning IEnumerator IEnumerable and returning. Moreover, there is a choice between non-generic interfaces and generic. Let's start by using the same iterator block for each of the four possibilities, and seeing the differences in the generated code. Throughout this article I will present the equivalent C # code that the compiler produces. Obviously, the compiler does not actually produce C #, but I've used reflector to decompile the code as C #.

Sample first Tour will only give the numbers 0 through 9 in sequence. Initially we will declare the method to return the nongeneric IEnumerator. Here is the complete code:

using System;
using System.Collections;

class Test
{
static IEnumerator GetCounter()
{
for (int count = 0; count < 10; count++)
{
yield return count;
}
}
}

Simple, right? Well, let's see what becomes after compilation. Hold your breath ...

State management

There are up to x pieces of state that the iterator type needs to keep track of:v

  • Your "virtual instruction pointer" (ie, when it comes)
  • Local variables
  • The initial parameter values, and this
  • The thread of creation (as shown above, and only in the case of IEnumerable, I will cover this more)
  • The last value given (ie current, which is trivial, not enough to warrant separate attention)

We'll look at each of the first three in turn

C# 4.0 goes dynamic

With C# 3.0 still so new that plenty of are only beginning to appreciate, let alone use, its new features it might seem premature to be discussing the next version of the most popular .NET language. Microsoft, however, has its designs for C# 4.0 well advanced, & the changes are so important that you might not recognise your favourite language after the upgrade. Now is the time to look over the horizon in the hope that finish users can influence the outcome.

The first thing to say is that C # has a special place in the panoply of. NET. When presented was essentially individual classes corresponding Windows developers with the expertise and the use of either VB or C + +. The division is clear as VB was easy to learn and easy to use but limited C, & + + was hard to imagine but could do nothing. You can even think of C + + as an object-oriented machine-independent assembly language if required, but VB is interpreted, well away from the machine building, was not so. Moreover, the distinction was also to take into account aesthetics - is disorderly and pragmatic VB and C + + pure logic. None of the courses of these characterizations is 100% true, are approximations to a true medium that is at least recognized by most developers, even if they had been discussing the fine details.

Not quite C++ nor VB

Currently they still have VB and C++ so where does C# fit in to today’s landscape? Again there is no absolute truth to be found, but a reasonable answer is that C# was originally designed to be an not as hard to use C++. It aspired to be more logical and cleaner, yet still easy (not as hard) to use. This ease of use not only derives from the language structure but from the simplicity of the Framework and the IDE (i.e. Visual Studio). The Framework simplifies everything by the simple act of dumping COM as a component object technology. The IDE makes generating a C# program much not as hard to generate than a C++ program basically by providing a drag-and-drop editor. User interface construction was seldom very complicated in C++, but equally its IDE support seldom rose much above the simple dialog box designer. (The fact that today you can use C++ as a standard .NET language complete with drag-and-drop interface designers is something of an anomaly that doesn’t fit in to the overall picture – a fact I and most other programmers pick to ignore in favour of C#.)

Thus C # is an "easy" to C + + with all its advantages? Not really. The problem is that C # is not as powerful as C + + and this is presented as a design decision. C # creates security, applications management and as such, simply can not provide the programmer with all hazardous installations of C + + pointers and direct memory access. (Of course, if you go out of their way to put them into practice, many of the dangerous mechanisms in C + + can be yours in C #, but that's another story). The result is that C # programmers migrating to C + + can be a little disappointed that his dangerous tools have been confiscated, but for the Visual Basic programmer who looks like a very sharp knife indeed. The only drawback to the programmer of VB migration is that C # is not as easy to use. It's a little logic and far too restrictive. They tend to insist on doing things "right."

You can not wriggle out of the object-oriented programming in C # and make this right is a big learning task. However, after the ideas are learned and object-oriented programming in C # seems natural, most VB programmers still can not understand why C # is strongly typed. Strong typing is designed to make it possible to detect stupid programming errors at design time rather than run time. The argument goes that automatically picks up any attempt to store apples in a container designed to store oranges. This sounds good and there is plenty of logic in the argument, but when a Visual Basic first encounter the problem like this:

string i;
i = 1;

Of course you can not assign an integer to a string - that's just dumb. However, a user of Visual Basic (or any user of a dynamic language) is far from being stupid and wonder why they have to go to so much trouble to make explicit type conversion when they have been accustomed to the compiler / Language is not all work for them. In short a dynamic language, does not care much for writing and attempts to make things "just work".
A dynamic language is not strongly typed because the write data is considered a matter of the mechanics of low-level hardware. An integer is just a way to store a number that makes some types of simple arithmetic, but are more difficult. In a dynamic language makes data that was said and if you say you do not reasonable, then an exception should be handled properly to create a solid program.

Wednesday, October 28, 2009

Delegates and events

People often find it difficult to see the difference between events & delegates. C# doesn't help matters by allowing you to declare field-like events which are automatically backed by a delegate variable of the same name. This editorial aims to clarify the matter for you. Another source of confusion is the overloading of the term "delegate". Sometimes it is used to mean a delegate type, & at other times it can be used to mean an instance of a delegate type. I'll use "delegate type" & "delegate instance" to distinguish between them, & "delegate" when talking about the whole topic in a general sense.

Delegate types

In some ways, you can think of a delegate type as being a bit like an interface with a single process. It specifies the signature of a process, and when you have a delegate instance, you can make a call to it as if it were a process with the same signature. Delegates provide other features, but the ability to make calls with a particular signature is the reason for the existence of the delegate concept. Delegates hold a reference to a process, and (for instance methods) a reference to the target object the process should be called on.

namespace DelegateArticle
{
public delegate string FirstDelegate (int x);
public class Sample
{
public delegate void SecondDelegate (char a, char b);
}
}

This code declares two types of delegates. DelegateArticle.FirstDelegate The first is that of a single int parameter and returns a string. The second is DelegateArticle.Sample.SecondDelegate char that takes two parameters and return nothing (because the return type is specified as null).

The rates stated here are derived from System.MulticastDelegate, which in turn derives from System.Delegate. In practice, you see only delegate types that are derived from MulticastDelegate. The difference between the Delegate and MulticastDelegate is largely historical, in beta. NET 1.0, the difference was significant (and annoying) - Microsoft sees the merger of the two types together, but decided it was too late in the release cycle to make a major change. You can almost pretend that only one type.
Any delegate who has inherited members believe their father types, a parameterized constructor of the object and IntPtr and three additional methods: Invoke, BeginInvoke and EndInvoke. Return to the constructor in a minute. The methods are not inherited from anything, because firms vary with the signature of the delegate is declared. Using the previous example code, the first delegate has the following methods:

public string Invoke (int x);
public System.IAsyncResult BeginInvoke(int x, System.AsyncCallback callback, object state);
public string Endinvoke(IAsyncResult result);

Reading Binary data in C #

This code is far from guaranteed to work. In particular, the FileStream might read only the first 10 bytes of the file in the buffer. The Read method is only guaranteed to block until some data are available (or the end of the sequence is reached), not until all the data available. That's where the return value (omitted in the above code) is vital. It is necessary to deal with cases that can not read all the data at once, and the loop until you read what you want. Here is a method you can use if you want to read a sequence in the whole matrix, not stopping until it is finished:

/// <param name="stream">The stream to read data from</param>
/// <param name="data">The array to read bytes into. The array
/// will be completely filled from the stream, so an appropriate
/// size must be given.</param>
public static void ReadWholeArray (Stream stream, byte[] data)
{
int offset=0;
int remaining = data.Length;
while (remaining > 0)
{
int read = stream.Read(data, offset, remaining);
if (read <= 0)
throw new EndOfStreamException
(String.Format("End of stream reached with {0} bytes left to read", remaining));
remaining -= read;
offset += read;
}
}

Sometimes you do not know the length of the stream in advance (for example, a current network) and only want to read the whole lot into a buffer. Here is a method to do just that:

// <summary>
/// Reads data from a stream until the end is reached. The
/// data is returned as a byte array. An IOException is
/// thrown if any of the underlying IO calls fail.
/// </summary>
/// <param name="stream">The stream to read data from</param>
public static byte[] ReadFully (Stream stream)
{
byte[] buffer = new byte[32768];
using (MemoryStream ms = new MemoryStream())
{
while (true)
{
int read = stream.Read (buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write (buffer, 0, read);
}
}
}

While the above is simple, not very efficient, because you just copy the data in the final, and probably several times between them. Here is a code that works well if you know the expected length of the data to start. (Although you can use stream.Length is not compatible with all streams.)

/// <summary>
/// Reads data from a stream until the end is reached. The
/// data is returned as a byte array. An IOException is
/// thrown if any of the underlying IO calls fail.
/// </summary>
/// <param name="stream">The stream to read data from</param>
/// <param name="initialLength">The initial buffer length</param>
public static byte[] ReadFully (Stream stream, int initialLength)
{
// If we've been passed an unhelpful initial length, just
// use 32K.
if (initialLength < 1)
{
initialLength = 32768;
}
byte[] buffer = new byte[initialLength];
int read=0;
int chunk;
while ( (chunk = stream.Read(buffer, read, buffer.Length-read)) > 0)
{
read += chunk;
// If we've reached the end of our buffer, check to see if there's
// any more information
if (read == buffer.Length)
{
int nextByte = stream.ReadByte();
// End of stream? If so, we're done
if (nextByte==-1)
{
return buffer;
}
// Nope. Resize the buffer, put in the byte we've just
// read, and continue
byte[] newBuffer = new byte[buffer.Length*2];
Array.Copy(buffer, newBuffer, buffer.Length);
newBuffer[read]=(byte)nextByte;
buffer = newBuffer;
read++;
}
}
// Buffer is now too big. Shrink it.
byte[] ret = new byte[read];
Array.Copy(buffer, ret, read);
return ret;
}

Multi-threading in .NET

One of the biggest understatements I've heard in a newsgroup was made by Patricia Shanahan, in a Java newsgroup in 2001: "Multi-threaded programming requires a little care." Multi-threading is probably one of the worst aspects of the programming period, and these days almost all application programmers need to understand that to some extent. This article serves as an introduction to multi-threading and gives some tips and suggestions for how to do it safely. Warning: I am not an expert in the field, and when the real experts start discussing in detail, my head starts spinning a little. However, I tried to pay attention to those who know what they are doing, and we hope the content of this article, at least part of a multi-threading "best practices".

This article uses the type of abbreviations in C # - int for Int32 etc. I hope this makes it easier for developers of C # to read, and will not impede any other developers too. It also monitors the talks only on how the C # variable declaration to be volatile and locking.

Multi-threaded "Hello, world"

Here is practically the simplest threading example that actually shows something happening:

using System;
using System.Threading;

public class Test
{
static void Main()
{
ThreadStart job = new ThreadStart(ThreadJob);
Thread thread = new Thread(job);
thread.Start();
for (int i=0; i < 5; i++)
{
Console.WriteLine ("Main thread: {0}", i);
Thread.Sleep(1000);
}
}
static void ThreadJob()
{
for (int i=0; i < 10; i++)
{
Console.WriteLine ("Other thread: {0}", i);
Thread.Sleep(500);
}
}
}

Understanding Properties in C#

Usually within a class, you declare a private field data and provide a set of public SET and GET methods to access data fields. This is a Nice programming practice, since the data fields can not be obtained directly from the class side. You must use the set / get methods to access data fields.

In C #, properties are nothing but a natural extension of data fields. Usually known as "smart fields" in the community C #. They know that data encapsulation and hiding is that the fundamental characteristics of any language object-oriented programming. In C #, data encapsulation is possible through classes or structures. By using various access modifiers etc as private, public, protected, internal, you can control the accessibility of class members.

//SET/GET methods
//Author: rajeshvs@msn.com
using System;
class MyClass
{
private int x;
public void SetX(int i)
{
x = i;
}
public int GetX()
{
return x;
}
}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc.SetX(10);
int xVal = mc.GetX();
Console.WriteLine(xVal);//Displays 10
}
}

Static Properties

C # also keeps static attributes, which belongs to the class instead of the objects of the class. All principles applicable to a static member is applicable to static properties also.

The following program shows a class with a static property.

/C# : static Property
//Author: rajeshvs@msn.com
using System;
class MyClass
{
private static int x;
public static int X
{
get
{
return x;
}
set
{
x = value;
}
}
}
class MyClient
{
public static void Main()
{
MyClass.X = 10;
int xVal = MyClass.X;
Console.WriteLine(xVal);//Displays 10
}
}

Properties & Inheritance

The properties of a base class may be inherited by a derived class.

//C# : Property : Inheritance
//Author: rajeshvs@msn.com
using System;
class Base
{
public int X
{
get
{
Console.Write("Base GET");
return 10;
}
set
{
Console.Write("Base SET");
}
}
}
class Derived : Base
{
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
d1.X = 10;
Console.WriteLine(d1.X);//Displays 'Base SET Base GET 10'
}
}

Properties & Polymorphism

A base class property polymorphicaly can be overridden in a derived class. But remember that as virtual switches, etc. being used to override property level, not at the level of access.

//C# : Property : Polymorphism
//Author: rajeshvs@msn.com
using System;
class Base
{
public virtual int X
{
get
{
Console.Write("Base GET");
return 10;
}
set
{
Console.Write("Base SET");
}
}
}
class Derived : Base
{
public override int X
{
get
{
Console.Write("Derived GET");
return 10;
}
set
{
Console.Write("Derived SET");
}
}
}
class MyClient
{
public static void Main()
{
Base b1 = new Derived();
b1.X = 10;
Console.WriteLine(b1.X);//Displays 'Derived SET Derived GET 10'
}
}

Property within a class can be declared as abstract using the abstract keyword. Remember that an abstract property in a class carries no code at all. The get / set access basically represented by a semicolon. In the derived class must apply to both set and get assessors.
If the abstract class contains only set access, they can implement two set of the derived class.

//C# : Property : Abstract
//Author: rajeshvs@msn.com
using System;
abstract class Abstract
{
public abstract int X
{
get;
set;
}
}
class Concrete : Abstract
{
public override int X
{
get
{
Console.Write(" GET");
return 10;
}
set
{
Console.Write(" SET");
}
}
}
class MyClient
{
public static void Main()
{
Concrete c1 = new Concrete();
c1.X = 10;
Console.WriteLine(c1.X);//Displays 'SET GET 10'
}
}

Implementing the Singleton Pattern in C#

There are several ways to implement the singleton pattern in C #. I present here, in turn order of elegance, with the most common initiative, which is not thread-safe, and work up to a full high lazily, thread-safe, simple and highly performant version. Note that the code here, do not use the personal älterer because it is the default for class members. In many other languages like Java, there is a different ruling, private and should be used.

The Singleton pattern is of two known models of software engineering. Essentially, a singleton is a class that only allows a single instance of itself to be made, and usually gives simple access to that instance. More commonly, not only can specify parameters to generate the instance - as the application otherwise the second one case, but with a parameter might be problematic! (If the same instance should have access to all applications with the same parameter, the factory pattern is more appropriate.) This article is concerned only with the situation in which no parameters are required. Usually, one requirement is that children are created only lazy - ie that the instance is not created until needed first.

  • A single constructor, which is private and no parameters. This prevents other classes of instances (which would be a violation of the guideline). Note that also prevents subclassing - if a product can be a subclass only once can be a subclass twice, and if each of these subclasses can create an instance, the pattern is violated. The factory pattern can be used if you need a single example of a base type, but the exact type is not known until runtime.
  • The class is sealed. This is unnecessary, strictly speaking, by the previous point, but can help to optimize the JIT things.
  • A variable that contains a reference to the single created instance, if any.
  • A means of obtaining public static reference to the single created instance, creating one if necessary.

Graphics, Multimedia, and Printing Recipes

. NET uses an asynchronous event model based on publication. To print a document, it becomes an instance System.Drawing.Printing.PrintDocument together their places, and then call its Print method, which schedules the print job. The common language runtime (CLR), then fire the BeginPrint, PrintPage, and events of the PrintDocument class EndPrint a new thread. To cover these events and the use of System.Drawing.Graphics oppose the exit provided data to the page. Graphics and text on a page are written the same way as you attract a window using GDI +. However, you may need to track their position on a page, because every Graphics class method requires explicit coordinates that indicate where draw.You to configure printer settings via the PrintDocument.PrinterSettings PrintDocument. DefaultPageSettings and properties. The property returns an object PrinterSettings PrinterSettings full (as described in recipe 8-11), which identifies the printer to use. The property offers a complete PageSettings DefaultPageSettings object that specifies the printer resolution, margins, orientation, and so on. You can set these properties in code, or use System.Windows.Forms.PrintDialog class for the user to make changes through the print dialog box standard Windows (as shown in Figure 8-9). In the Print dialog box, the user can select a printer and select the number of copies. The user can also click the Properties button to configure advanced options such as page layout and printer resolution. Finally, the user can accept or cancel the print operation, click OK or Cancel.

The example of the supplies from a form with a single button. When the user clicks the button, the application makes a new PrintDocument grants the user to configure the settings, and then initiates an asynchronous print operation (provided the user clicks OK). An event handler responds to the event PrintPage and writes several lines of text and picture.

using System;

using System.Drawing;

using System.Windows.Forms;

using System.Drawing.Printing;

using System.IO;

namespace Apress.VisualCSharpRecipes.Chapter08

{

public partial class Recipe08_14 : Form

{

public Recipe08_14()

{

InitializeComponent();

}

private void cmdPrint_Click(object sender, EventArgs e)

{

// Create the document and attach an event handler.

PrintDocument doc = new PrintDocument();

doc.PrintPage += this.Doc_PrintPage;

// Allow the user to choose a printer and specify other settings.

PrintDialog dlgSettings = new PrintDialog();

dlgSettings.Document = doc;

// If the user clicked OK, print the document.

if (dlgSettings.ShowDialog() == DialogResult.OK)

{

// This method returns immediately, before the print job starts.

// The PrintPage event will fire asynchronously.

doc.Print();

}

}

private void Doc_PrintPage(object sender, PrintPageEventArgs e)

{

// Define the font.

using (Font font = new Font("Arial", 30))

{

// Determine the position on the page.

// In this case, we read the margin settings

// (although there is nothing that prevents your code

// from going outside the margin bounds.)

float x = e.MarginBounds.Left;

float y = e.MarginBounds.Top;

// Determine the height of a line (based on the font used).

float lineHeight = font.GetHeight(e.Graphics);

// Print five lines of text.

for (int i = 0; i < 5; i++)

{

// Draw the text with a black brush,

// using the font and coordinates we have determined.

e.Graphics.DrawString("This is line " + i.ToString(), font, Brushes.Black, x, y);

// Move down the equivalent spacing of one line.

y += lineHeight;

}

y += lineHeight;

// Draw an image.

e.Graphics.DrawImage(

Image.FromFile( Path.Combine(Application.StartupPath, "test.jpg") ),

x, y);

}

}

}

}

Using Web Services from Your C# Application

Over the years, one of the great dilemmas facing software developers and big business is how to make the data available to those both inside and outside, without sacrificing security and make it efficient. When it was assumed that the information being shared was to create tapes and disks, email, and then import the data. Another problem for software developers are giving users powerful features without having to spend hundreds of hours trying to give users want they want. Web Services, also called XML Web Services provides developers with these skills and more.
In addition, exposure data can also provide developers and perform remote actions by creating a Web service that people can use elsewhere. An example is a web service connected to a webcam in the ballpark of the Seattle Mariners (called Safeco Field) that lets me see the ball game on my computer in my office.
One of the really great features of Web services is that you can create with them. NET and C # if you have the full version of Visual Studio. NET.
Web services provide solutions to tasks that either do not make sense for you to create or maintain the code, or for which it should have access to the data available outside of another company or facility. A couple of examples of the use of Web services are receiving contributions from the stock market or weather information service anywhere in the world. These examples are used in this chapter to discuss what Web services are and how you can use in their applications.
When talking about the issues that I mentioned in this chapter:

  • Provides an overview of Web services and how you can use in C # Express.
  • Explain what web services are available and how to find them.
  • Shows how to create references in their application to the desired Web services.
  • Shows how to use Web services in their own applications, with examples of the addition of stock quotes and weather information for Web services.

Manipulating Strings in C#

Most applications require the use of chains in one form or another. Chains are required for the construction of SQL statements to access a database, for example. Knowing how to manipulate strings is useful in analyzing requests from Web clients and in building a response to the client.
Strings are reference types. You have been learning about the reference rates gradually in each chapter. The category of reference types include types defined with the keyword class. As you recall, you have to create an object before you can use a type variable. For example:

Account acct = new Account();

Before you create an object variable is null. The same rule applies to the chains. The string variables when declared are zero. However, what makes the ropes, they also have interesting features of value types (integers, longs, booleans, etc, for example). C # allows you to assign a string object without using the new operator, thus:

string sqlAuthors = "SELECT * FROM AUTHORS";

The previous code creates a new string object. Other features include how you can use the == and! = Operators to compare two string objects.
So what is a string? Internally you can think of a string as an array of characters. When you create a string object, in essence, two objects are created in one. The first object is an instance of the String class. The string class has members that describe the physical attributes of the chain, such as the length of the string. The second object that is created is a buffer to maintain the character of the string. The buffer is just a piece of memory to store the characters in the string. The string variable that point to the string declaration of external object, which in turn points in the character buffer.

What makes string types very interesting is that in. NET strings are immutable: the buffer can not be changed. Languages such as C # allow you to treat the string variable as a variable rate. For example, let you add another string to the string in the variable. However, this is an illusion provided by the compiler. Actually, when you change the contents of the string, the compiler of the question. NET runtime to create a brand-new string object.
String objects consume memory, and if you're not careful, may end up consuming too much memory. At some point that the memory must be recovered. . NET Framework uses a mechanism known as garbage collection to recover the memory.

At the end of this chapter you will learn about StringBuilder, which lets you create a string variable to a single character buffer that can be modified. When you are finished editing the buffer StringBuilder, StringBuilder you can ask to produce a string object from the results. Using StringBuilder will help you minimize the number of string objects that must be created, and this in turn, reduce the number of garbage collections that must occur to remove objects from memory.

C# Coding Solutions

In the previous chapters, the stress was on how to use the .NET API. All of the examples were illustrated using C#, but the examples did not use any particular feature of C#. The examples could have been executed with VB.NET or any other .NET language. That changes in this chapter, as the focus is on the C# programming language. Specific features of the language will be dissected & analyzed. Sometimes patterns will be used, & other times not. In the overall system of this chapter, the idea is to give you a better understanding of what C# is capable of & not capable of.

C# Canonical Forms

Many object-oriented languages including C #, anything Don'T bid to force software developers to create well designed. No better example of this than when using C + + to implement an object-oriented design. C # is a little more structured than C + +, for example, can not be created without static functions that exist outside the context of a defined type. However, C # does not obligate you to create software that adheres to known practices of good software design.

The C + + community quickly identified some canonical forms useful for the design of rates to meet a specific purpose. Really, these canonical forms are nothing more than checklists, or recipes, you can use while designing new classes. Before a pilot can clear an aircraft to return through the door, you must go through a strict checklist. The purpose of this chapter is to identify and checklists for creating robust in the world types in C #.

In exploring these checklists, we must consider what kind of behavior will require new types of objects you are creating. For example, the new rate will be Cloneable? In other words, it can be copied? Is it supported the new order type, if the cases are placed in a collection? What does it mean to compare two references of this kind of object for equality? In other words, you want to know if the two references are to the same instance? Or want to know if two recent cases have exactly the same state? These are the types of questions you should ask when creating a new type.

Design Pattern Implementation in C#

Design patterns make it not as difficult to reuse successful designs & architectures. Design patterns help you choice design alternatives that make a technique useful & avoid alternatives that compromise reusability. They help make a technique independent of how its objects are created, composed, & represented. An abstract factory provides an interface for generating families of related objects without specifying their concrete classes.

What is a design pattern

A design pattern is a proven design solution to a common problem faced by software developers. Design patterns became popular with the emergence of object analysis and design (OOAD). Design patterns are designed to help developers deliver higher quality, more maintainable software products in less time and less cost.

What is a design pattern

A design pattern is a proven design solution to a common problem faced by software developers. Design patterns became popular with the emergence of object analysis and design (OOAD). Design patterns are designed to help developers deliver higher quality, more maintainable software products in less time and less cost.

Design patterns are:

  • Units - They embody design knowledge the collaboration of classes and objects, the distribution of responsibility, and design issues.
  • Object oriented - OOAD principles are incorporated, for example, low coupling, high cohesion.
  • Reusable - They are adaptable, flexible, general solutions to the kinds of issues with broad applicability. Design patterns simplify the task facing the developer.

How are design patterns classified

Design patterns are categorized to facilitate learning and dissemination. They are classified according to the underlying problems that concern, ie according to usage.
The three main categories of design patterns are:

Design patterns of behavior - Describe how the class and object interaction and how responsibilities are distributed among them.
Creational design patterns - to address the object creation process. Creational design patterns encapsulate knowledge about how, when and by whom it is instantiated.
The structural design patterns - the address of the composition of classes and objects.

Tuesday, October 27, 2009

C# Operators

Although most of C# ’ s operators should be familiar to C and C++ developers, this section discusses the most important operators for the benefit of new programmers and Visual Basic converts, as well as to shed light on a number of the changes introduced with C#.

C# supports the operators listed in the following

 

Category Operator
Arithmetic + - * / %
Logical & | ^ ~ && || !
String concatenation +
Increment and decrement ++ --
Bit shifting << >>
Comparison == != < ><= >=
Assignment = += -= *= /= %= &= |= ^= <<= >>=
Member access (for objects and structs) .
Indexing (for arrays and indexers) [ ]
Cast ( )
Conditional (the ternary operator) ?:
Delegate concatenation and removal +, -
Type information sizeof is typeof as
Overflow exception control checked unchecked
Indirection and address [ ]
Namespace alias qualifier : :
Null coalescing operator ??

 

Note that four specific operators (sizeof, *, ->, and &, given in the table below), however, are available only in unsafe code (code that is independent of C # 's type - security),  "Memory Management and Pointers." It is also important to note that the sizeof operator keywords, when used with the. NET Framework 1.0 and 1.1, require unsafe mode. This is not a since the requirement. NET Framework 2.0.

Category Operator
Operator keywords sizeof (for .NET Framework versions 1.0 and 1.1 only)
Operators * - > &

Creating Arrays

The Array class is abstract, so you cannot generate an array by using a constructor. However, instead of using the C# syntax to generate array instances, it is also possible to generate arrays by using the static CreateInstance() process. This is very useful if you don ’ t know the type of the elements in
advance, because the type can be passed to the CreateInstance() process as a Type object. The following example shows how to generate an array of type int with a size of 5. The first argument of the CreateInstance() process requires the type of the elements, & the second argument defines the size. You can set values with the SetValue() process, & read values with the GetValue() process.

Array intArray1 = Array.CreateInstance(typeof(int), 5);
for (int i = 0; i < 5; i++)
{
intArray1.SetValue(33, i);
}
for (int i = 0; i < 5; i++)
{
Console.WriteLine(intArray1.GetValue(i));
}
You can also cast the created array to an array declared as int[] :
int[] intArray2 = (int[])intArray1;

The CreateInstance() process has plenty of overloads to generate multidimensional arrays & also to generate arrays that are not 0 - based. The following example creates a 2 - dimensional array with 2 × 3 elements. The first dimension is 1 - based; the second dimension is 10 - based.

int[] lengths = { 2, 3 };
int[] lowerBounds = { 1, 10 };
Array racers = Array.CreateInstance(typeof(Person), lengths, lowerBounds);

Setting the elements of the array, the SetValue() method accepts indices for every dimension:
racers.SetValue(new Person(“Alain”, “Prost”), 1, 10);
racers.SetValue(new Person(“Emerson”, “Fittipaldi”), 1, 11);
racers.SetValue(new Person(“Ayrton”, “Senna”), 1, 12);
racers.SetValue(new Person(“Ralf”, “Schumacher”), 2, 10);
racers.SetValue(new Person(“Fernando”, “Alonso”), 2, 11);
racers.SetValue(new Person(“Jenson”, “Button”), 2, 12);

Although the array is 0 - based can assign to a variable with the standard notation C #. You just
must be careful not to push the limits.

Person[,] racers2 = (Person[,])racers;
Person first = racers2[1, 10];
Person last = racers2[2, 12];

Friday, October 23, 2009

Delegate Example in C#

MathOperations In this example defines a class that has a couple of static methods to perform two The repo. Then you use delegates to call these methods. The math looks like this.

class MathOperations
{
public static double MultiplyByTwo(double value)
{
return value * 2;
}

public static double Square(double value)
{
return value * value;
}
}
You call up these methods like this:
using System;
namespace Wrox.ProCSharp.Delegates
{
delegate double DoubleOp(double x);
class Program
{
static void Main()
{
DoubleOp[] operations =
{
MathOperations.MultiplyByTwo,
MathOperations.Square
};
for (int i=0 ; i < operations.Length ; i++)
{
Console.WriteLine(“Using operations[{0}]:”, i);
ProcessAndDisplayNumber(operations[i], 2.0);
ProcessAndDisplayNumber(operations[i], 7.94);
ProcessAndDisplayNumber(operations[i], 1.414);
Console.WriteLine();
}
}
static void ProcessAndDisplayNumber(DoubleOp action, double value)
{
double result = action(value);
Console.WriteLine(
“Value is {0}, result of operation is {1}”, value, result);
}
}
}

Delegates in C#

The following code snippet demonstrates the use of a delegate. It is a long - winded way of calling the ToString() scheme on an int :

private delegate string GetAString();
static void Main()
{
int x = 40;
GetAString firstStringMethod = new GetAString(x.ToString);
Console.WriteLine(“String is {0}”, firstStringMethod());

(continued)

// With firstStringMethod initialized to x.ToString(),
// the above statement is equivalent to saying
// Console.WriteLine(“String is {0}”, x.ToString());
}

In this code, you instantiate a delegate of type GetAString , & you initialize it so it refers to the ToString() process of the integer variable x . Delegates in C# always syntactically take a six – parameter constructor, the parameter being the process to which the delegate will refer. This process must match the signature with which you originally defined the delegate. So in this case, you would receive a
compilation error if you tried to initialize the variable firstStringMethod with any process that did not take any parameters & return a string. Notice that, because int.ToString() is an instance process (as opposed to a static six), you require to specify the instance ( x ) as well as the name of the process to initialize the delegate properly.

The next line actually uses the delegate to display the string. In any code, supplying the name of a delegate instance, followed by brackets containing any parameters, has exactly the same effect as calling the method wrapped by the delegate. Hence, in the preceding code snippet, the Console.WriteLine()
statement is equivalent to the commented - out line.

In fact, supplying brackets to the delegate instance is the same as invoking the Invoke() method of thedelegate class. Because firstStringMethod is a variable of a delegate type, the C# compiler replaces
firstStringMethod() with firstStringMethod.Invoke() :

firstStringMethod();
firstStringMethod.Invoke();

For less typing, at every place where a delegate instance is needed, you can pass the name of the address. This is known by the term delegate inference . This C# feature works as long as the compiler can resolve the delegate instance to a specific type. The example initialized the variable firstStringMethod of type GetAString with a new instance of the delegate GetAString :

GetAString firstStringMethod = new GetAString(x.ToString);
You can write the same just by passing the method name with the variable x to the variable
firstStringMethod :
GetAString firstStringMethod = x.ToString;

The code that is created by the C# compiler is the same. The compiler detects that a delegate type is required with firstStringMethod , so it creates an instance of the delegate type GetAString & passes the address of the technique with the object x to the constructor.

“” Be aware that you can ’ t type the ( & ) as x.ToString() & pass it to the delegate variable. This would be an invocation of the method. The invocation of x.ToString() returns a string object that can ’ t be assigned to the delegate variable. You can only assign the address of a method to the delegate variable.” ”

Sponsored Ad

More Related Articles

Website Update

Followers