1. Trang chủ
  2. » Công Nghệ Thông Tin

Overview of Csharp ebook

33 159 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Overview of C# CS331 Structure of a C# Program // Specify namespaces we use classes from here using System; using System.Threading; // Specify more specific namespaces namespace AppNamespace { // Comments that start with /// used for // creating online documentation, like javadoc /// <summary> /// Summary description for Class1. /// </summary> class Class1 { // Code for class goes here } } Defining a Class class Class1 { static void Main(string[] args) { // Your code would go here, e.g. Console.WriteLine("hi"); } /* We can define other methods and vars for the class */ // Constructor Class1() { // Code } // Some method, use public, private, protected // Use static as well just like Java public void foo() { // Code } // Instance, Static Variables private int m_number; public static double m_stuff; } C# Basics • C# code normally uses the file extension of “.cs”. • Note similarities to Java – A few annoying differences, e.g. “Main” instead of “main”. • If a namespace is left out, your code is placed into the default, global, namespace. • The “using” directive tells C# what methods you would like to use from that namespace. – If we left out the “using System” statement, then we would have had to write “System.Console.WriteLine” instead of just “Console.WriteLine”. • It is normal for each class to be defined in a separate file, but you could put all the classes in one file if you wish. – Using Visual Studio .NET’s “P)roject, Add C)lass” menu option will create separate files for your classes by default. Getting Help • If MSDN is installed – Online help resource built into Visual Studio .NET. – Help Menu, look up C# programming language reference – Dynamic Help • If MSDN is not installed, you can go online to access the references. It is accessible from: – http://msdn.microsoft.com/library/default.asp – You will have to drill down to VS.NET, Documentation, VB and C#, and then to the C# reference. • Both include numerous tutorials, or search on keywords Basics: Output with WriteLine • System.Console.WriteLine() will output a string to the console. You can use this just like Java’s System.out.println(): System.Console.WriteLine(“hello world “ + 10/2); will output: hello world 5 • We can also use {0}, {1}, {2}, … etc. to indicate arguments in the WriteLine statement to print. For example: Console.WriteLine(“hi {0} you are {0} and your age is {1}”, “Kenrick”, 23); will output: hi Kenrick you are Kenrick and your age is 23 WriteLine Options • There are also options to control things such as the number of columns to use for each variable, the number of decimals places to print, etc. For example, we could use :C to specify the value should be displayed as currency: Console.WriteLine(“you have {0:C} dollars.”, 1.3); outputs as: you have $1.30 dollars. • See the online help or the text for more formatting options. Data Types • C# supports value types and reference types. – Value types are essentially the primitive types found in most languages, and are stored directly on the stack. – Reference types are objects and are created on the heap. C# Type .NET Framework type bool System.Boolean byte System.Byte sbyte System.SByte char System.Char decimal System.Decimal double System.Double float System.Single int System.Int32 uint System.UInt32 long System.Int64 ulong System.UInt64 object System.Object short System.Int16 ushort System.UInt16 string System.String Built-In Types Ref type Automatic Boxing/Unboxing • Automatic boxing and unboxing allows value types can be treated like objects. • For example, the following public methods are defined for Object: Equals Overloaded. Determines whether two Object instances are equal. GetHashCode Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table. GetType Gets the Type of the current instance. ToString Returns a String that represents the current Object. We can then write code such as: int i; Console.WriteLine(i.ToString()); int hash = i.GetHashCode(); This is equivalent to performing: z = new Object(i); Console.WriteLine(z.ToString()); First version more efficient due to automatic boxing at VM level Structures • struct is another value type – A struct can contain constructors, constants, fields, methods, properties, indexers, operators, and nested types. – Declaration of a struct looks just like a declaration of a class, except we use the keyword struct instead of class. For example: public struct Point { public int x, y; public Point(int p1, int p2) { x = p1; y = p2; } } • So what is the difference between a class and struct? Unlike classes, structs can be created on the stack without using the keyword new, e.g.: Point p1, p2; p1.x = 3; p1.y = 5; • We also cannot use inheritance with structs. [...]... a single chunk of memory of size 30*3*sizeof(int) and creates a reference to it We use the formulas for row major order to access each element of the array • The following defines a 30 x 3 array using an array of arrays: int[][] arr = new int[30][3]; • To an end user this looks much like the previous declaration, but it creates an array of 30 elements, where each element is an array of 3 elements –... Java arrays Arrays are always created off the heap and we have a reference to the array data The format is just like Java: Type arrayname = new Type[size]; • For example: int arr = new int[100]; • This allocates a chunk of data off the heap large enough to store the array, and arr references this chunk of data More on Arrays • The Length property tells us the size of an array dynamically Console.WriteLine(arr.Length);... outputs the value of 3 because x is passed by value to method foo, which gets a copy of x’s value under the variable name of a Passing by Reference • C# allows a ref keyword to pass value types by reference: public static void foo(int ref a) { a=1; } static void Main(string[] args) { int x=3; foo(ref x); Console.WriteLine(x); } The ref keyword must be used in both the parameter declaration of the method... be of type array we would use: public void foo(int[] data) • To return an array we can use: public int[] foo() • Just like in Java, if we have two array variables and want to copy one to the other we can’t do it with just an assignment – This would assign the reference, not make a copy of the array – To copy the array we must copy each element one at a time, or use the Clone() method to make a copy of. .. reference and may be changed Outputs the value of 1 since variable a in foo is really a reference to where x is stored in Main Passing Reference Variables • If we pass a reference variable (Objects, strings, etc ) to a method, we get the same behavior as in Java • Changes to the contents of the object are reflected in the caller, since there is only one copy of the actual object in memory and merely multiple... Console.WriteLine(FindMin(arr, new CompareDelegate(compare1))); Console.WriteLine(FindMin(arr, new CompareDelegate(compare2))); } The output of this code is: abracadabra foo (using compare1, alphabetic compare) (using compare2, length of string compare) Next Lecture • Here we have covered all of the basic constructs that exist in the C# language under the Common Language Runtime! • Next we will see how to use various... type Strings • The built-in string type is much like Java’s string type – Note lowercase string, not String – Concatenate using the + operator – Just like Java, there are a variety of methods available to: • find the index Of matching strings or characters • generate substrings • compare for equality (if we use == on strings we are comparing if the references are equal, just like Java) • generate clones,... is an array of 3 elements – This gives us the possibility of creating ragged arrays but is slower to access since we must dereference each array index – Just like Java arrays Related to Arrays • Check out the ArrayList class defined in System.Collections – ArrayList is a class that behaves like a Java vector in that it allows dynamic allocation of elements that can be accessed like an array or also by... implement stop } void Turn() { // Code here to implement turn } } Method that uses the Interface: void GoForward(IDrivable d) { d.Start(); // wait d.Stop(); } Reading Input • To input data, we must read it as a string and then convert it to the desired type – Console.ReadLine() will return a line of input text as a string • We can then use type.Parse(string) to convert the string to the desired type... array Delegates • C# uses delegates where languages such as C++ use function pointers • A delegate defines a class that describes one or more methods – Another method can use this definition, regardless of the actual code that implements it – C# uses this technique to pass the EventHandlers to the system, where the event may be handled in different ways Delegates Example Compare1 uses alphabetic comparison, . Overview of C# CS331 Structure of a C# Program // Specify namespaces we use classes from here using System; using. indexers, operators, and nested types. – Declaration of a struct looks just like a declaration of a class, except we use the keyword struct instead of class. For example: public struct Point { public. Options • There are also options to control things such as the number of columns to use for each variable, the number of decimals places to print, etc. For example, we could use :C to specify

Ngày đăng: 23/10/2014, 15:20

Xem thêm:

TỪ KHÓA LIÊN QUAN

Mục lục

    Structure of a C# Program

    Basics: Output with WriteLine

    Passing a Reference Variable

    Passing Reference Var by Reference

TÀI LIỆU CÙNG NGƯỜI DÙNG

  • Đang cập nhật ...

TÀI LIỆU LIÊN QUAN