+ All Categories
Home > Documents > A Programmers Introduction to C#

A Programmers Introduction to C#

Date post: 24-Feb-2016
Category:
Upload: sheba
View: 51 times
Download: 0 times
Share this document with a friend
Description:
A Programmers Introduction to C#. Keith Elder Microsoft MVP http://keithelder.net/blog/. Assumptions. I assume you Have 1 – 2 years of programming experience Understand the basic concepts of Variables Loops Arrays Can type over 40 words per minute (if you are following along). - PowerPoint PPT Presentation
66
A Programmers Introduction to C# Keith Elder Microsoft MVP http://keithelder.net/blog/
Transcript

A Programmers Introduction to C#

A Programmers Introduction to C#Keith ElderMicrosoft MVPhttp://keithelder.net/blog/AssumptionsI assume youHave 1 2 years of programming experienceUnderstand the basic concepts ofVariablesLoops ArraysCan type over 40 words per minute (if you are following along)

C# SyntaxWhen I learn a new language I like to know basic things about the syntax. I find that if I understand the basics of the syntax and what is allowed and what is not allowed, I can start typing faster. The first thing we are going to do is go through some basics of the language itself.3All Lines Must End in ;CorrectIncorrectint x = 5;int x = 5Just like other C style languages, all lines must end with a semi-colon ;4Variables Must Declare TypeCorrectIncorrectint x = 5;x = 5;The keyword int is declaring that the value of x going to hold an integer.In this example, we are creating a variable called x and using the assignment operator which is just the equals sign. The variable x is holding the value of 5. In C#, we have to declare the type of data the varible will hold. The keyword int is a keyword in C# which is a type that is typing the variable of x to an integer.

(click)

Because we must declare a type for all variables, C# is referred to as a strongly typed language. Because C# is strongly typed, we get a lot of benefits as a developer. One we get compile type checking. This means when we compile our program, the compiler can check to make sure we arent doing something bad. Because things are typed within C# we also know a lot about a particular type, and this assists in Visual Studio generating intellisense and generating code for us. Also, it allows us to refactor our application with great certainty that we havent messed anything up.

If you arent familiar with the term refactoring it means the ability to change something in the program, this may be a variable name, take code and generate a method from it, etc.5Supported C# TypesC# type keywords.Net Framework TypeboolSystem.BooleanbyteSystem.BytesbyteSystem.SbytecharSystem.ChardecimalSystem.DecimaldoubleSystem.DoublefloatSystem.SingleintSystem.Int32unitSystem.UInt32longSystem.Int64ulongSystem.UInt64objectSystem.ObjectshortSysytem.Int16ushortSystem.UInt16stringSystem.StringC# keywords are technically aliases that point to the .Net framework type. Both are one in the same. One is just quicker to type. Each C# keyword matches a .Net framework type. Sometimes you may see string or String. They mean the same thing, the only difference is the ones on the left are quicker to type.6Type Cannot Be ChangedCorrectIncorrectint x = 5;

int x = 5;x = foo;This will result in a compile error. Once a type has been established for a variable, the type cannot change to another data type.Once a variable has been declared as a specific type, that type cannot change.

(click)

In the incorrect example above, we declare a variable as an integer, and then in the next line we try to put a string into the variable. This will result in a compilation error.7Strings must be in quotesCorrectIncorrectstring x = foo bar;

string x = foo bar;string x = foo bar;char x = a;

char x = a;All strings must be in double quotes. In some languages it doesnt matter if you use double or single quotes. In C#, double quotes infers a string of characters and a single quote refers to a single character, which is a different type than string, it is the char type.8OperatorsC# uses standard mathematical operators+, -, /, *, , =, Expression operators&&||==!=Assignment operators=, +=, *=, -=, *=

http://msdn.microsoft.com/en-us/library/6a71f45d.aspxConcatenating Stringsstring x = foo bar;string y = x + some new string;

In C# we use the + plus operator to concatenate strings. I will note this early on that this is not the most optimal way to handle concatentating strings in a lot of cases. Typically we will use a built-in mechanism called StringBuilder to build up and concat strings. For simple string concats, this does work just fine.10Case SensitiveCorrectIncorrectint x = 5;int Z = 5;int y = x + Z;int x = 5;int Z = 5;int y = x + z;C# is a case sensitive language. It is important to follow a standard when naming variables, well discuss this later on. Just remember the language is case sensitive.11If / Elseif (expression){ } else{

}if (expression){ } else if (expression){

} else{

}int x = 5;if (x > 5){ x = 10; } else{ x = 0;}TIP: If you only have one line in your if block, you can skip the curly braces.int x = 5;If (x % 2 == 0) CallSomeMethod();C# uses curly braces to define blocks of code. A block of code can be not just if/else but other things as well see later on. For example Foreach loops, while loops, classes, and namespaces all use curly braces to define their blocks. This is used by the parser and is the same for other languages like C, C++, Perl, PHP, and even scripting languages like Bash.

Now that weve covered some of the absolute basics with the language, lets play around with C# a bit. NOTE: There will be some things we havent covered yet in this demo. Well cover them in just a bit, for now, please just ignore them.12Demo Fun with variblesCreate a new console application. Initialize some variables, show addition, subtraction, leave off a ; at the end, show the parse error, change the type of a variable to a string and show how to add it, write some if / else blocks based on a calculation.13Very Simple Programclass MyFirstProgram{ static void Main() { int x = 5; int y = 10; int z = x + y; }}C# Quick FactsThis is the most simple program one can write in C#. This program isnt all that interesting because it doesnt interact with the user or store the calculation but it does compile and work. There are some new things we havent seen yet, so let me cover those first. To start with lets start with the static void Main(). Every C# program must have a Main() to start with. This is typical of other C style languages as well. Main() is just a function if you want to think of it like that for now. We note that the Main function is surrounded with curly braces, again this denotes a block within C#. Surrounding the Main function is another block. The syntax is really simple. The keyword class and then the name of the program. Well learn in a bit more about classes.

For now just remember that every C# program must have a Main() to initialize the program.14Breaking Down C# - NamespaceNamespaceAbstract container providing organization to items.Typically organized by:CompanyProductTeamSub-TeamEtc.Example:Microsoft.Learning.CsharpNamespaceClassMethod1Method2Fields and Properties

The fact is the very simple program we just saw is REALLY simple, it will not represent what code in C# will look like. We are going to break down C# and put this puzzle back together.

We start with something called a Namespace.

(click)

It is just an abstract container. The syntax is really simple, there is the keyword namespace and then you give it a name. As the diagram shows, the namespace encloses a class completely. You may be wondering, Well, what kind of name do I give it. There are some standards around this. Typically we name things based on our company, then the product we are working on, and the we subclass from there. Namespaces can be broken down into multiple names by placing a dot (.) between the names like: Microsoft.Learning.Csharp.

This would signify that all the code within this namespace is owned by Microsoft corporation, and deals with learning of the Csharp language. Pretty simple huh? When you define namespaces in your code, they should be simple and make sense to other developers as well.15Breaking Down C# - Namespacenamespace SkunkWorks{ public class Loan { public decimal loanAmount; public bool isApproved ; }}namespace Vendor{ public class Loan { public decimal loanAmount; public bool isApproved ; public int creditScore ; }}

You may be wondering why we do this. Well, there is a reason to the madness. One classic example is say we own a company called SkunkWorks and have created some code called Loan. Down the road we need to interact with a third party vendor who also has some code called Loan. How would the C# compiler know which one to load? The answer is it wouldnt. Thus we surround the code with a namespace to help in knowing which one we want to load or deal with. The screen shot at the bottom signifies that visual studio doesnt know which one to use and it is prompting the developer, asking which one it should reference, the Vendors or SkunkWorks. 16Demo - NamespacesBreaking Down A C# - ClassA class is just a blue print for an object.An object is an allocated region of storage.An object doesnt exist until memory is allocated.A class holds data (properties/fields) and is made up of one or more methods (functions) .NamespaceClassMethod1Method2Fields and Properties

Weve already seen several examples of something called a class. It was in the previous example, and our very simple program example we looked at earlier.

(click)

A class is nothing more than a blue print. Think of it like building a house. Blue prints are typically drawn up by the architect and handed to the foreman. Within a house though, there are lots of things. If we were to model building a house in C# wed have thousands of classes that would define each item within a house. A nail, brick, concrete, door facings, wire, paint, etc would each have a class.

Lets take a Door for example and dig down a little further with it. As part of the blue print, wed need to know if it was made of wood or metal. Wed need to know the manufacturer, cost, height, width, etc. Now I know some of you are very mindful of database design so lets relate this conversation to that. If you are a database person, think of all the things youd have to know about a door and design a database table to hold that information. Each column of a database would represent what we call a field or property within our class. We see this in red within the diagram.

Taking this example a step further, a door can perform certain actions. For example a door can open and close. But not all doors open and close at the same speed. We may have an automatic garage door that has to have special sensors to know when something walks in front of the door so if our dog runs into the garage while it is coming down, the door will not close on them. These actions are what we call methods. Methods are just fancy names for functions.

Weve established that a Class is a blue print, but really when we speak of a door, we think of a physical object dont we? The same is true in C#. We think of it like this. I create a class first to define my door (fields, properties, methods). Then I create a door. Think of this as the act of manufacturing a door. Once the door is created we have a physical object. In C#, when we manufacture a Door, we do so by creating what we call an instance of it. The only difference in the real world and our C# world is a Door in C# is an allocated region of storage in memory. Thus, when you here the term object all that means is weve created something from a Class and it now lives in memory.

Lets look at how wed do that in C#.18Breaking Down C# Classnamespace SkunkWorks{ public class Loan { public decimal loanAmount; public bool isApproved; }}Loan myLoan = new Loan();When an instance of a Loan is created in memory, this becomes an object. Thus the variable myLoan is an object.FieldsClassNamespaceClassMethod1Method2Fields and Properties

In this example we have a class called Loan. Weve identified some properties of this loan object, the loan amount and whether or not it is approved. To create an object out of the class Loan we do what is called instantiate it. The syntax is simple and is no different that what we saw earlier when we created the variable x of type int.

First, we have to declare a type. Our type is Loan because that is the name of the class. Then we give this a name. The name given here is called myLoan.

Then we use the keyword called new and then the name of our class followed by parentheses.

We call this creating an instance of Loan. When this line of code is executed myLoan is technically an object. That means it is in memory.

A question you might ask now is, When we define a class it looks like we are creating our own types, is that true?

The answer to that is YES! You are creating your own types.

This is the basic premise of object oriented programming. When writing programs in functional languages, it is hard to express all of the things a specific item can do and all the data it can hold. When you create a class, you are in fact creating a new type, similar to int, string and so on.

This concept is extremely powerful and allows you the developer to create more concise and readable code.

19Breaking Down C# Classnamespace SkunkWorks{ public class Loan { public Loan() { } public decimal loanAmount; public bool isApproved; }}A constructor is the default function/method that executes when a class is instantiated. If one doesnt exist, a default constructor is provided by the compiler. ConstructorClassMethod1Method2ClassField and PropertiesConstructorIf the syntax of creating a new Loan object is a little confusing because of the parentheses at the end, this may help. All classes in C# have something called constructor. A constructor is a generic term used in any object oriented language. A constructor is named the same name as the class. It is technically a method/function. We use them to initialize values in our classes.

Sometimes we use them to set default values and other times we use them carry out some other type of processing.

In our example of creating a new Door object, me may request a new serial number for the door, or we may update inventory automatically or increment a global counter of how many doors weve created.

If you create a class that doesnt have a constructor, it isnt the end of the world. One will be provided for you by the compiler. We call this a default constructor.20Fields and Properties. Yeah but I hold the data

Oh yeah. Well I expose the data. So nah!

Breaking Down C# - FieldsFields hold dataField FactsBy default they are private to other classes (more later)Fields hold the dataPlaced at the top of classes outside of any methodsPrivate fields are usually notated with an _ (underscore) prefixThey are named camel cased with first letter starting with a lowerCase

Fields hold data within our classes. Think of them as just varibles. A variable holds data.

Weve seen previous examples with them in a class.

You can call them anything you want, but they should make sense given the context of the class.

In other words, avoid names like x, y, z, I, etc. They should have real names. Just like we identified earlier where a door has a lot things we need to know about it, serial number, manufacturer, etc.22Breaking Down C# - PropertiesExpose DataProperty FactsUsed to expose field dataUsed to bind data to user interface elementsAllows for pre and post logic before getting or accessing dataUses accesors to set and get field dataTypically always marked public (more later)Properties always are named in CamelCase, using no underscores or dashes

C# uses a concept called Properties which allow programmers to expose data using fields.

Think of them as wrappers for fields. We mentioned earlier that fields by default were private. Notice the keyword public in from of the LoanAmmount property. Well cover more about this in a second but what is happening here, is this.

We have a piece of data called _loanAmount. Current that data is only viewable within the class itself. However, we want to expose this to other classes. But we also want to control things like who, how, when, etc. By using a Property and something called accessors, we can allow other classes to get at this field data and change the value if we chose. We can have one or both of the accessors (get / set). Thus we can control what happens.

For example, if we take off the set accessor to ths property, that means nothing, can change the loan amount, they can only read that value. We call this a read-only property.

Which way you will go will be determined by the business.23Properties Real World Example

Here is a more real world example of how this would play out.

In this example we are first validating the information that goes into _loanAmount before setting it and we are also calling a function called OnPropertyChanged. Youll see this a lot in C# classes where classes need to keep track of their state. In other words, have they been changed or altered, or maybe they are marked for deletion.

In the else block we throw an exception, which tells the program something bad happened. Well touch more on that down the road.24Who can see what?Public means that anyone can access itPrivate means that only other members can access it

The field docCompleted will not be able to be viewed from classes outside of Loan. The C# keyword private signifies it is private within the scope of the class itself. Public means it can be seen by other classes.Weve mentioned several times the keyword public and private. Here is a deeper look at those.

In this example. We have a class that has three fields. Two are marked public, and one is marked private.

The one marked private is not accessible to any objects outside. In this example, only the two fields could be accessed externally in other objects.

At first this raise the question why would I would want to do that? The truth is there are lots of reasons. Well learn later on some principles of object oriented programming and how this plays into those principles.

Also note the class itself is marked public. Several things can be marked public or private:

FieldsPropertiesMethodsClasses

And other things we havent learned yet25Accessing Methods and Properties of an InstanceUse the . (period) after the instance name of your object to call methods in the class and access properties.Intellisense will guide you in VS

Demo Our first C# ClassCreating a classConstructorFieldsPropertiesPublic / PrivateBreaking Down C# - MethodsThink of methods as actions that classes can perform.Take a function, put it in a class, we call it a method.C# doesnt allow functions to live and breathe outside of a class. Thus, all we have is methods.Methods can access other methods within the class and properties, and call other methods in other classes. public class Loan { public decimal loanAmount; public bool isApproved;

public void MarkApproved() { IsApproved = true; OnMarkedApproved(); } }Using our example earlier about the Door, we know we can open and close doors. If we were to model a Door class in code we would have to represent this in the class. We do this with methods. A method is just another name for a function.

Because all the code we write in C# has to be within a class, functions cannot live outside of a class, thus all of our functions are inside of a class, and because of this we need another word to distinguish between functions that are within a class, we call these methods.

Just like functions in other languages, methods can take parameters and return a value, or they can just carry out a task and return nothing. They can even return objects. 28Breaking Down C# - Methods

Access levelReturn typeMethod nameParameters

Lets break down the syntax of a method in C#.

The first thing that much be declared is the access level. As mentioned previously, weve learned two types of access levels so far:

PrivatePublic

If no access level is defined, private is used by default.

(click)

The next thing is the return type (see types we previously talked about, also this type may be a defined class).

(click)

Next up is the name of the method. The name of the method in .Net starts with upper case and is camel cased.

Method names should be descriptive, should be actions or verbs. Functions / methods always do something.

In other words, the class is the noun, the method is the verb.

(click)

Next up is parameters.

Essentially what we are doing is defining a variable that will be passed into the method. The variables are only used within the method itself. We would say these variables are scoped within the method block. This also goes for any variable created within a block, it is scoped to that block.

Parameters must specify the type and then a name.

Parameters are placed within parentheses.

(click)

To call a method, we simply type the name, and pass in the values we want, separated by commas. In this example, since AddTwoNumbers returns a number, we are going to capture that output in another variable called myNum.

Methods that do not return anything use a return type of void.

29Demo Making our classes do somethingUsing Statementsnamespace ConsoleApplication{ class Program { static void Main() { Loan myLoan = new Loan(); myLoan.LoanAmount = 1000000; } }}Using statements specify which Namespaces to use to resolve classes.using System;using Vendor;One thing we havent covered31Breaking Down C# - StaticReferenced through the type not the instance

The best way to explain the static keyword is to show an example of it.

In this example we are calling into a .Net library located in System.dll. This example is calling into the DateTime class. The DateTme class is an extensive class that deals with and handles dates and times. It is something that any developer writing in C# will eventually use.

When we type a dot after the name of the DateTime class, we see a lot of options appear within intellisense.

Are you noticing that we didnt create a new instance of DateTime like we did with numbers and the Loan object earlier?

The icons that are purple represent methods. The blue ones, public fields, and the white icon where the word Now is, is a property.

The static keyword allows us to access the method, field, or property without having to create an instance of the object in memory. In other words, we get access to what we want through the type, in this case the type is a DateTime.

For programmers that are coming from a functional background, when something is marked as static, it will feel just like one is calling a function.

NOTE: The use of static is something that much be used wisely. Marking things static and not knowing the consequences can result in memory leaks, poor performance and maintainability. 32Breaking Down C# - StaticCan be used withFieldsMethodsPropertiesOperatorsEventsConstructorsCannot be used with indexers and deconstructors

Our initial simple program had the keyword static in it.

Static methods cannot access properties and fields within a class unless they also are marked static. Again, this is something you should try to avoid when programming to follow good object oriented principles.33Demo Using / StaticWorking with ClassesWeve now explored everything in our sample program. Theres one thing we need to spend a lot more time on and that is classes. Classes are first class citizens in C# and OOP languages. They allow us to define our own types and use those types within a given domain context. Lets look at some examples and explore further how classes will be used.35Use a Class to Define an Object

A New Object From a Class Is An Instance

The variable lassie is the instance of the object.

Use the . (period) after the instance of your object to call methods in the class and access properties.

Think of it like this. Lassie didnt exist until we created Lassie, it is the birth of Lassie from a class we are talking about here. Now that Lassie was born or created, we have an instance. 37Classes can be re-used

In this example we have 3 different instances of the class dog that represent three different dogs. Through the methods in the class we can control which dog does what. Each dog can have their own set of characteristics that define each one. Simon could be a chocolate cocker spaniel, and Max could be a buff cocker spaniel. Regardless of which color and breed they are, they all still bark and sit!38A Primer on Object Oriented ProgrammingInheritanceEncapsulationAbstractionPolymorphismThe Animal Object

These are all animals. Some share common characteristics and others dont. For example, some of these animals have fur, others have feathers. Some bark, some chirp, others moo. A class defines the abstract characteristics of the thing it is describing. Some people call it a blueprint. For example, the class Dog would consist of traits shared by all dogs, such as fur color, the ability to bark and sit. A class should be recognized to a non-programmer familiar with the problem-domain, meaning the characteristics should make sense within the given context. 40Four principles of Object Oriented ProgrammingInheritanceAbstractionEncapsulationPolymorphismThere are four pillars of OOP as they are called. They form the building blocks for understanding how a developer should build their applications.41Inheritance Dogs Gone Wild

InheritanceConstructorAlthough this class doesnt have FurColor in it, the value is derived from the base class.Rule: Classes that are subclassed inherit all the properties and methods of their parent class.In C#, a class can be inherited or subclassed. This example shows that we implemented a Collie class. The only difference between the Collie class and a Dog class is Collies should have a default color of white and tan. To achieve this, we use what is called the CONSTRUCTOR. The constructor is a fancy name for a METHOD with the same name as the CLASS. When a new instance of the object is created, the code within the constructor is executed, thus allowing an object to do pre-initialization. In more complex examples, this may initialized other objects, call other methods, etc. Just like any method, a constructor can take arguments as well.

We call these classes that inherit from a base class sub-classes.42Subclasses Different Strokes For Different Folks

Subclasses can implement different characteristics.Subclasses can override base class behavior.

Adding the keyword virtual to a method means it can be overridden in a base class.Classes that are subclassed can implement their own properties and methods to extend the characteristics provided by the base class. Subclasses can override behavior. In order to do this, the developer that made the base class had to add the keyword virtual to the method in the base class to allow this to occur. Once the virtual keyword is added, a developer can use the override keyword in the subclass to override the method. They can also invoke the base class behavior by calling: base.MethodName(). 43AbstractionAbstraction is simplifying complex reality by modeling classes appropriate to the problem

Depending on the context of the problem trying to be solved, sometimes we need to think about abstracting away complexity. For example, if Im counting the number of pets I have, do I really have to know the type? No. I am just counting Animals. If someone said, how many dogs do you have then I need to know which type of animal it is Im dealing with. Abstraction is all about simplifying things down to the appropriate problem at hand.

Again, these are principles of object design and things you as a developer need to keep in mind as you model your classes.44EncapsulationCreating an object that keeps track of its state internally using private fields and uses public properties and methods to let other classes work with only the part of the internal data they need to see.

When a dog barks, we really dont need to know the ins and outs of how he/she goes about barking. We want to encapsulate those gory details and simply expose those as Bark(). One can also think of a cell phone. When you press the green dial button on a cell phone, we didnt have to know how to communicate with a cell phone tower, and translate the number into a routing cell tower ID and so on. All we did is press the dial button, everything underneath is encapsulated around the dial button.

In the example above, the method Bark is public, but the methods InHale and Exhale are not public, they are private. Again, we dont need to expose that to other developers using our class.

In a functional programming language, wed see all three methods, Bark, Inhale and Exhale. One developer may call Ihale and then Exhale, and another may use the simplier Bark method.

Because we are able to hide the details of how something works, developers can focus more on the what they want to do. 45PolymorphismThis word means Many forms. Its taking an object, and use it in a method or statement that expects something else.

Feed takes any Animal. We are down casting the type to Animal.

In the example above you may be asking yourself the following question:

I thought we had to know the type we were passing around? If so, how is it that we are able to call the same method Feed(), but yet pass a duck to one and a dog to another? Isnt that like passing a string to one and an int to another?

The answer is through inheritance we are able to do this. In this example, both Duck and Dog inherited from a base class called Animal. After all, they are both animals. Because they both inherit from animal, we can down cast their type to a lower common denominator and therefore code to that, thereby opening up the door to allow our objects to take on different forms.46Interfaces Taking Abstraction One Step FurtherIn C#, a class can only inherit from one other classAn Interface is a way of providing abstractionInterfaces let you define a bunch of methods and properties a class must have

Heres the problem. Even though our Chihuahua class had a Tremble() method on it, there are other dogs that need to tremble as well. To follow the OOP principle of Polymorphism and Abstraction, we need a way to be able to cast up or down a dog class.

To do this, when more than one thing needs to share, we create an interface. An interface is more or less a contract. It defines how other classes can interface with it.

Lets look at an example.47Interfaces Taking Abstraction One Step Further

This class implements the ITremble InterfaceNow that weve defined an Interface of ITremble, any animal class that implements that interface we know is tied to the contract of that interface. This assists in Polymorphism, whereby we may need to make all the animals tremble in an array of animals, but only those that implement that interface. We can use the keyword is to determine if a class implements a given Interface.48Interface FactsInterfacesQuick FactsStart with an uppercase IIDisposable, IEnumerable, IListAny class that implements an Interface has to implement ALL methods and propertiesA class can implement one or more Interfaces (separate the names by comma)VS Shortcut Tip: Alt-Shift-F10 to implement methods

Demo Interfaces, Abstraction, Inheritance, Oh my!Commenting Code// single lines/// for summaries/* */ block//int x = 5; /// /// This is what kicks the program off. /// /// static void Main(string[] args) { }/* this is a comment */Demo - CommentsValue Type vs Reference Type4foobarhelloint foo = 4;string bar = hello;Value TypesintfloatboolByteReference TypesstringobjectlistregexValue types store the value and reference types store a reference to the value. The value types are how most people think of variables. Reference types work a little bit like pointers in other languages. Since C# is a managed language these pointers are hidden away so the programmer does not have access to them.

Assignment of reference types does not duplicate the value as is done with value types. The reference types only copy the reference to the value. This means that the information for a reference type is only stored in that one spot and multiple variables can point to it.

Reference types can be null. Value types cannot be null.53Value Type vs Reference TypeauthornameKeithstring name = Keith;string author = null;author = name;http://aspalliance.com/1682_What_to_Know_About_Value_Types_and_Reference_Types_in_C.all Arrays More than one at a timeArray FactsExamplesC# supports the following collectionsAn array can be Single-Dimensional, Multidimensional or Jagged. The default value of numeric array elements are set to zero, and reference elements are set to null. A jagged array is an array of arraysArrays are zero indexed: an array with n elements is indexed from 0 to n-1. Array elements can be of any type, including an array type. Array types are reference types derived from the abstract base type Array. Since this type implements IEnumerable , you can use foreach iteration on all arrays in C#.

C# supports many collection types. An array is one of the simplest collections we can use. C# supports single, multi and jagged arrays.

Arrays in C# are zero based arrays. That means the indice starts at ZERO. This is important to understand because some languages start at the indice 1.

The syntax is extremely simple for arrays in C#.

We use the [] to indicate an array. This can be placed at the end of any type (even classes youve created).

Just like creating a new instance of a class, we use the new keyword and then our type. The only difference is we use the []. We can pass in a number and this is how many elements will be in the array. We can also set and declare elements in the same line.

There are various ways to create arrays, just use the one that expressess your intent the best.

Multidimenional arrays allow you to build matrices. Here is a sample to show you how this would look to build a multidimentional array.

(click)

55LoopsForeach loopsFor loopsWhile loops foreach (var item in collection){ Console.WriteLine(item.Property); } for (int i = 0; i < length; i++){ Console.WriteLine(i);}while (expression) // x < 5{ }TIP: Use code snippets to stub these out.Demo - ArraysNow we are getting somewhere!Other Ways To Store Lots of DataSystem.CollectionsCollection Classes - System.CollectionsDo you need a sequential list where the element is typically discarded after its value is retrieved?Queue FIFOStack LIFOAccess by indexArrayListStringCollectionAccess by keyHashtableSortedListListDictionaryStringDictionaryAccess by key or indexNameValueCollection

Collection Classes - System.CollectionsSort elements differently from how they were enteredHashtable sorts its elements by their hash codesSortedList sorts by keyArrayList provides a sort method that can take an IComparer implementation as a paramIf you need fast searchesListDictionary is faster than Hashtable with fewer than 10 itemsDictionary provides faster lookup

Demo System.CollectionsGenericsYou should thank me for showing you this.Basics of GenericsA generic type definition is a class, structure, or interface declaration that functions as a template, with placeholders for the types that it can contain or use.System.Collections.Generics New as of .Net 2.0Provides a way to generically express re-usable codeProvides compile time type checkingCreates a shorter syntax

Basics of GenericsList is the generic class that corresponds to ArrayListThe Queue, Stack, and SortedList are generic classes correspond to the respective nongeneric classes with the same names.

Demo - GenericsEventsAllow your objects to respond when something occursAn object should worry about itself, not other objectsBaseball Simulatorball.OnBallInPlay(70, 82);ballBallInPlay event raisedpitcher objectumpire objectfan object

public class StatusEventArgs : EventArgs { public string Status { get; set; }

public StatusEventArgs() { } }

public class Loan { public event EventHandler StatusChanging; public event EventHandler StatusChanged;

public string Status { get; set; } public void ChangeStatus(string newStatus) { OnStatusChanging(newStatus); this.Status = newStatus; OnStatusChanged(newStatus); }

public void OnStatusChanging(string status) { var handler = StatusChanging; if (handler == null) { return; } handler(this, new StatusEventArgs { Status = status }); }

public void OnStatusChanged(string status) { var handler = StatusChanged; if ((handler == null)) { return; } handler(this, new StatusEventArgs { Status = status }); }

}66


Recommended