Getting started with C# Programming


Published on

Session is about how to write first program in C#. Also discusses variables, Data Types, CTS, Value Type, Reference Type, string, object, dynamic, Type Casting, Boxing Unboxing, Console.ReadLine(), Console.WriteLine()

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Getting started with C# Programming

  1. 1. Getting Started With C# Programming Bhushan Mulmule m
  2. 2. Watch Video on
  3. 3. First C# Program Complication Execution Command Line Args Variables CTS Types Value and Reference Types Type Inference Type Casting Boxing And Unboxing Constants Reading Keyboard inputs
  4. 4. First C# Program
  5. 5. //This is my first C# program using System; namespace HelloWorld { class FirstProgram { static void Main() { Console.WriteLine("Hello World"); Console.ReadKey(); } } }
  6. 6. Compilation And Execution >CSC FirstProgram.cs >FirstProgram.exe
  7. 7. Variables  a variable is a storage location and an associated symbolic name (an identifier)  Different types of variables can be declared to store different type of data.  Variables needs to be declared before use  Typical syntax to declare variable is: < type > < name > For Example: int a; float b; a b
  8. 8. //Variable Demo //Program to add two numbers using System; namespace VariableDemo { class Program { static void Main(string[] args) { int no1, no2, result; no1 = 10; no2 = 20; result = no1 + no2; Console.WriteLine("Result = " + result); Console.ReadKey(); } } } no1 no2 Result 10 20 30
  9. 9. CTS Types  Data types in .NET are specified by CTS. Language datatype maps to CTS datatype. For example, int of C# maps to System.Int32 of CTS.  CTS have two categories of types: Value Type and Reference Type  Every type derived from System.Object. (Directly of Indirectly)  Data types are classes or structs that supports certain methods. For example, string s = i.ToString();  C# has 16 predefined types  13 value types and  3 reference types (string, dynamic, object) .
  10. 10. 25a 67436b 3.14c 343.54d -e nullf Stack Heap 45600 Strings are cool! 45600 g 25 int a; //32 bits long b; //64 bits float c; //32 bits double d; //64 bits char e; //16 bits string f; int g; string h; a = 25; b = 6743674654783474; c = 3.14F; d = 4443534534.54; e = '-'; f = "Strings are cool!"; g = a; //Copies actual value h = f; //Copies reference of object ... ... h 45600
  11. 11. Value Type  Value types store value on stack  All value types are derived implicitly from the System.ValueType.  Assigning one value type variable to another copies the actual value.  While passing to function value types by default passes parameters by value.  13 built-in value types are available (listed on next slide)  User defined value type can be created using keywords:  struct and  enum
  12. 12. Name CTS Type Description sbyte System.SByte 8 bit signed integer short System.Int16 16 bit signed integer int System.Int32 32 bit signed integer long System.Int64 64 bit signed integer byte System.Byte 8 bit unsigned integer ushort System.UInt16 16 bit unsigned integer Uint System.UInt32 32 bit unsigned integer ulong System.UInt64 64 bit unsigned integer float System.Single 32 bit single precision floating point double System.Double 64 bit single precision floating point decimal System.Decimal 128 bit high precision decimal notation bool System.Boolean Represents true of false char System.Char Represents a single 1b bit character (Unicode)
  13. 13. Reference Type  Variables of reference types store actual data on heap and references to the actual data on stack.  The actual data stored on heap is referred as object.  Assignment operation copies reference.  While passing to function reference types by default passes parameters by reference.  Three build in reference types are available: string, dynamic and object  User defined reference type can be created using keywords:  class  Interface  delegate
  14. 14. string  The string type represents a sequence of zero or more Unicode characters. string is an alias for String in the .NET Framework.  equality operators (== and !=) are defined to compare the values of string objects, not references.  Strings are immutable--the contents of a string object cannot be changed after the object is created. Instead new object gets created  Verbatim string literals start with @ and are also enclosed in double quotation marks. For example: @"c:DocsSourcea.txt“. The advantage is that escape sequences are not processed
  15. 15. static void Main(string[] args) { string s1 = "Bhushan"; s1 = s1 + " Mulmule"; Console.WriteLine("s1 = " + s1); string s2 = s1; s2 = “Logic & Concepts"; if(s1 == s2) Console.WriteLine("s1 and s2 are same"); else Console.WriteLine("s2 is modified"); string filePath = @"c:documentstraining"; Console.WriteLine("FilePath = " + filePath); Console.ReadKey(); } s1 Stack Heap 45600 Bhushan 45600 Bhushan Mulmule 45700 s2 45700 45700 Logic & Concepts 45800 45800
  16. 16. dynamic  bypass compile-time type checking. Instead, these operations are resolved at run time.  behaves like type object in most circumstances. Except not resolved or type checked by the compiler  variables of type dynamic are compiled into variables of type object. Therefore, type dynamic exists only at compile time, not at run time.  simplifies access to COM APIs such as the Office Automation APIs, and also to dynamic APIs such as IronPython libraries, and to the HTML Document Object Model (DOM).
  17. 17. static void Main(string[] args) { dynamic dyn; object obj; dyn = 1; obj = 1; System.Console.WriteLine(dyn.GetType()); System.Console.WriteLine(obj.GetType()); //Compile time error: Operator '+' cannot be applied to operands of type 'object' and 'int' obj = obj + 3; //bypasses compile-time type checking. Instead, resolves at run time. dyn = dyn + 3; }
  18. 18. object  The object type is an alias for Object in the .NET Framework.  All types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object.  can assign values of any type to variables of type object.
  19. 19. Access Name Description public Equals(Object) Determines whether the specified object is equal to the current object. public static Equals(Object, Object) Determines whether the specified object instances are considered equal. protected Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. public GetHashCode Serves as a hash function for a particular type. public GetType Gets the Type of the current instance. protected MemberwiseClone Creates a shallow copy of the current Object. public static ReferenceEquals Determines whether the specified Object instances are the same instance. public ToString Returns a string that represents the current object.
  20. 20. Type Inference  Local variables can be given an inferred "type" of var instead of an explicit type.  The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement.  The variable must be initialized at the time of declaration.  The initializer cannot be null.  The initializer must be an expression.  You can’t set the initializer to an object unless you create a new object in the initializer.  The inferred type may be a built-in type, an anonymous type, a user-defined type, or a type defined in the .NET Framework class library.
  21. 21. static void Main(string[] args) { var no = 25; var pi = 3.14F; var e = 2.718281828459045; var msg = "wow!!!"; var isTrue = true; Console.WriteLine(no.GetType()); Console.WriteLine(pi.GetType()); Console.WriteLine(e.GetType()); Console.WriteLine(msg.GetType()); Console.WriteLine(isTrue.GetType()); Console.ReadKey(); } Output System.Int32 System.Single System.Double System.String System.Boolean
  22. 22. Nullable Types  Nullable types represent value-type variables that can be assigned the value of null. (Reference types already support the null value.)  Can be declared as: <datatype>? <variablename>; for example int? x;  Can be initialized as int? x = 10; or int? x = null.  Very usefull for database operations
  23. 23. static void Main() { int? num = null; if (num.HasValue == true) { System.Console.WriteLine("num = " + num.Value); } else { System.Console.WriteLine("num = Null"); } // y is set to zero int y = num.GetValueOrDefault(); Console.ReadKey(); }
  24. 24. Type Casting  Type casting is converting an entity of one data type into another.  Types of Type Cating  Implicit Typecating  Explicit Typecasting
  25. 25. Implicit Typecasting  Automatically done by compiler (in following circumstances)  Built-in numeric types: if a narrow type is being assigned to wider type. (For example: long = int)  Reference types: Derived class is being assigned to base class. int a = 25; float b; b = a; 0b a 25 Implicit Typecasting 25.0
  26. 26. Explicit Typecasting  Need to be done if implicit typecating is not supported  For example: int = (int) long;  Can be done using typecast operators or helper methods  Data can be lost while doing Explicit conversion  Explicit conversion may fail if not possible.  Available techniques: (int)s, int.Parse(s), Convert.ToInt32(s), As operator float x = 56.3f; int y; y = (int)x; 56.3x 0y Explicit Typecasting 56
  27. 27. ... int a = 25; double b = 10.5; double c; c = a + b; //a is implicitly casting to double int d; d = a + (int)b; //b has to Explicitly typecast to integer string s1 = "100"; int i; i = int.Parse(s1); //using helper method Parse of datatype itself string s2 = "200"; i = Convert.ToInt32(s2); //using Convert class for type conversions object obj = 10; string str; str = obj as string;
  28. 28. Boxing And Unboxing  Boxing:  Process of converting value type into reference type  Boxing is implicit  Unboxing:  Process of converting reference type into value type  Unboxing is explicit  Note:  Attempting to unbox null causes a NullReferenceException.  Attempting to unbox a reference to an incompatible value type causes an InvalidCastException.
  29. 29. null static void Main(string[] args) { int a = 25; object o; o = a; //boxing Console.WriteLine("o = {0}", o.ToString()); int b; b = (int)o; //unboxing Console.WriteLine("b = {0}", b.ToString()); Console.ReadKey(); } 25a 67436o 0b 25 Stack Heap 67436 Boxing Unboxing 25
  30. 30.  Constant is a variable whose value cannot be changed throughout its lifetime.  Must be initialized at the time of declaration.  Always implicitly static.  Advantages:  Makes program easier to read.  Makes program easier to modify.  helps to prevent mistakes. Constant
  31. 31. static void Main(string[] args) { const float pi = 3.14F; int r = 5; float area = pi * r * r; Console.WriteLine("Area = " + area); pi = 3.1415F; Console.ReadKey(); }
  32. 32. Reading Input using Console.ReadLine()  Console.ReadLine() is static method to read keyboard inputs  It reads a line at a time  A line is defined as a sequence of characters followed by a carriage return (hexadecimal 0x000d), a line feed (hexadecimal 0x000a), or Environment.NewLine. The returned string does not contain the terminating character(s).
  33. 33. static void Main(string[] args) { int no1, no2, result; Console.Write("Enter Number 1: "); no1 = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter Number 2: "); no2 = Convert.ToInt32(Console.ReadLine()); result = no1 + no2; Console.WriteLine("{0} + {1} = {2}", no1, no2, result); Console.ReadKey(); } 0 0result no2 0no1 25 50 75
  34. 34. Command Line Arguments  Arguments or parameters that we can pass to Main() method from command propt. For Ex: >greet C#  Main method need to define in one of the following ways:  The parameter of the Main method is a String array represents the command-line arguments. static void Main(string[] args) static int Main(string[] args)
  35. 35. //Command line arguments demo using System; namespace HelloWorld { class Greet { static void Main(string[] args) { if(args.Length == 1) Console.WriteLine("Hello " + args[0]); else Console.WriteLine("Invalid Arguments"); Console.ReadKey(); } } } C#args 0
  36. 36. Bhushan Mulmule bhushan.mulmule@dotnetvideotutorial. com