380 likes | 470 Views
By: Meg Yahl. C#. History of C#. “Father of C#” Anders Hejlsberg Created in 2000 Built on .NET Framework . What’s in a Name?. C# is COOL! C-like Object Oriented Language But… so are a lot of other things Trademarking nightmares. Looking Sharp. C. Design.
E N D
By: Meg Yahl C#
History of C# • “Father of C#” Anders Hejlsberg • Created in 2000 • Built on .NET Framework
What’s in a Name? • C# is COOL! • C-like Object Oriented Language • But… so are a lot of other things • Trademarking nightmares
Design • “Create a first class modern language on the CLR platform that would appeal to the curly braces crowd: the C++ programmers of the world at the time, and competitively, the Java programmers.” – Anders Hejlsberg • Versioning • Designed to be backwards compatible
Identifier Names • Only letters, numbers, and underscores • Syntactically must start with a letter or an underscore • Actually starting with an underscore is (generally) considered bad practice. • Okay in certain situations • Confusing when used elsewhere
So… What’s Your Type? • Case sensitive • Strongly typed • Statically typed (mostly) • C# 4.0 introduced dynamic binding • Type-safe • Keyword unsafe • Value Types • Reference Types • Generic type parameters • Pointer types. • Reliability
Some COOL Qualities • “C# supports a Unicode character set, which means that letters from any language can be stored and used. You can also use any Unicode character to name your variables.” • Keywords can be used as variable names IFF prefixed with the @ symbol. • The @ symbol doesn’t form part of the identifier itself. • Readability class class {...} // Illegal class @class {...} // Legal
“Everything is an Object” • Not quite… • C# has boxing and unboxing • Boxing is like taking the value type and wrapping it up in a little box, which can then be treated like an object. • Unboxing simply reverses this process. • “Every non-pointer type in C# is convertible to an object” (Lippert).
Value Types • Store actual data • Don’t need new operator since “each value type has an implicit default constructor that initializes the default value of that type” (Microsoft Corporation). • Can be represented both in boxed and unboxed form. • All numeric types • Char type • bool type • Custom structs • Custom enum types • Cannot contain the null value • “nullable types feature does allow for value types to be assigned to null” (Microsoft Corporation).
More Value Types • Encapsulates small groups of related variables • May contain: • constructors • constants • fields • methods • properties • indexers • operators • events • nested types • Can “implement an interface, but they cannot inherit from another struct” (Microsoft Corporation). • User-defined data type • Useful for providing “an efficient way to define a set of named integral constants that may be assigned to a variable” (Microsoft Corporation). • Readability Struct Enum
Reference Types • Made of an object and a reference to that object • Only store references to data, not the data itself • “Two or more reference type variables can refer to a single object in the heap, allowing operations on one variable to affect the object referenced by the other variable” (Afana). • Class types • Array types • Delegates • Interface types • Reliability
Arrays • Zero-based • One type only • Rectangular int[][] multiArray= new int[3,2]; • Jagged (Array of Arrays) int[][] jaggedArray = new int[3][]; jaggedArray[0] = new int[5]; jaggedArray[1] = new int[4]; jaggedArray[2] = new int[2]; Writability • Square brackets for declaration and indexing • Memory efficient • Know own length • System.Array class has useful properties and methods • “All array indexing is bounds-checked by the runtime” (Albahari 35).
Generic Types • Useful for writing reusable code that can accommodate different types. • Like a template that gets filled in once needed • Can increase type safety and reduce casting and boxing • Writability • Reliability
Pointers • Directly manipulate memory • Only usable with unsafecode and IDE setting • “Pointer types are primarily useful for interoperability with C APIs, but may also be used for accessing memory outside the managed heap or for performance-critical hotspots” (Albahari 170). • Reliability • “Warning: There be dragons here.” – Comments in code
Expression/Assignment Statements • Primary Expressions • “Composed of operators that are intrinsic to the basic plumbing of the language” (Albahari 45). • Void Expressions • No value • Expression Statements • Can stand alone as valid statements • “Must either change state or call something that might change state.” (Albahari 49). • Includes • Assignment expressions (including increment and decrement expressions), • Method call expressions (both void and nonvoid), • Object instantiation expressions” (Albahari 49).
Operators • Transform and combine expressions • Numerous operators of different types • Many of these operators can also be overloaded. • Assignment operator is = • Compound assignment operators • +=, -+, *=, /=, etc. • Writability • Readability • Primary • Unary • Multiplicative • Additive • Shift • Relational and type testing • Equality • Logical AND • Logical XOR • Logical OR • Conditional AND • Conditional OR • Conditional • Assignment
StatementLevel Control Structures • Selection • Iteration • Unconditional branching (jump statements) • Most control expressions are specified in parentheses and must be of type Boolean.
Selection/Iteration • if-else constructs • switch statements • do…while • while • for • foreach…in… • C# supports nested if-else constructs and loops • Can nest as deep as desired, but code can become messy • Readability Selection Iteration (Loops)
GOTO It was my idea first :)
Jump Statements • break • Immediately ends the execution of the body of an iteration or switch • continue • Immediately jumps to the end of a loop and starts the next iteration • goto • Allows code execution to jump to another label within the statement block • When used irresponsibly, code can become nearly unreadable. • Many programmers have reserved goto as an absolute last resort, or even shunned it altogether. • return • Can appear anywhere in a nonvoid method. Their job is to exit the method and return an expression of the method’s return type • throw • Detects the occurrence of an error and throws the relevant exception, which is then handled by the programmer • Jump statements “obey the reliability rules of try statements” (Albahari 54). • Specifically, “a jump out of a try block always executes the try’s finally block before reaching the target of the jump, [and] a jump cannot be made from the inside to the outside of a finally block” (Albahari 54). This is important in exception handling
Subprograms • In C#, subprograms in general are referred to as methods. • Can have any type, including user-defined types and void. • C# does not allow nested methods. • Only have stack-dynamic local variables • Type-checking: “C# requires the type of a ref actual parameter to match exactly the type of its corresponding formal parameter” (Sebesta 410).
Parameter passing • Pass-by-value (in-mode parameters) • C# default • Passes a copy to the method • Fast for scalars, but uses more storage • Pass-by-result (out-mode) • Same pros and cons as pass-by-value • Also risks possible parameter collision • C# requires the out modifier in the formal parameter list when using out-mode parameters. • Pass-by-value-result (inout-mode) • Combo with all the good and bad • More storage and time cost • Greater chance of variable mixups • Pass-by-reference (inout-mode) • Requires keyword ref before formal and actual parameters • Transmits an access path, usually just an address, to the called subprogram • More efficient with time and space • Slower formal parameter access • Can create aliases, which can really hurt readability and reliability “C# allows methods to accept a variable number of parameters, as long as they are of the same type.” (Sebesta 393)
Methods As Parameters (Delegates) • Typically, passing methods as parameters is handled by passing pointers to the method instead of the actual method itself. • “In C#, the power and flexibility of method pointers is increased by making them objects. These are called delegates, because instead of calling a method, a program delegates that action to a delegate” (Sebesta 420). • Essentially, a delegate is like a messenger. • The program invokes a delegate, which in turn invokes the desired method. • This provides a level of abstraction from the caller and the target method.
Delegate Example: Call Center • Let the delegate class be thought of as a telemarketer call center. • Each telemarketer (the delegate) has a list of phone numbers (the target methods). • This list can contain zero (null) or more phone numbers. • The telemarketer must go through list in order (a multicastdelegate) before they can leave work. • At the end of a long day, only the last number called really stands out in the telemarketer’s memory. • The call center can also have automated dialers with prerecorded messages (genericdelegates). • In the case of a technical support center, the employees (delegates) are presented with a particular situation that has occurred (event), and they must resolve the situation accordingly (eventhandling).
Overloaded Methods • C# allows overloaded methods • However, they must have some distinction from each other or the program cannot tell which method to use. • This ambiguity is avoided by varying the number, order, or type of parameters. • Because C# allows mixed-mode expressions, different return types does not help to distinguish the methods • The meaning is determined by the actual parameter list when the method is called.
Generic Methods • A generic method is a method “whose computation can be done on data of different types in different calls” (Sebesta 397). • DRY (“don’t repeat yourself.”) • C# generic methods are unique in that “the actual type parameters in a call can be omitted if the compiler can infer the unspecified type.” (Sebesta 427)
Abstract Data Types/Encapsulation • Interfaces do not have to be declared abstract since they are always implicitly abstract, as are their members. • C# interfaces are similar to Ada package specifications in that they specify their members, but they do not implement them. • The class or struct that inherits the interface is responsible for implementing every member specified in the interface. • These “interface members are always implicitly public and cannot declare an access modifier, [so] implementing an interface means providing a public implementation for all its members” (Albahari 92). • It is interesting to note that structs cannot inherit from classes, but they can implement interfaces. • Additionally, classes can only inherit from one class, but they can implement more than one interface. Albahari states that objects can be implicitly casted to any interface that they implements (Albahari 92).
Support for Object-OrientedProgramming • C# was essentially built with object-orientation in mind. • C# has a few unique object-oriented features: • Unified type system; • All types ultimately share a common base type • Classes and interfaces; • Classes are types • An interface is like a class except it is only a definition for a type, not an implementation (Albahari 1). • Many languages do not support multiple inheritance, but C# can by implementing multiple interfaces. • Properties, methods, and events. • Properties are function members that encapsulate a piece of an object’s state, such as a button’s color or a label’s text. • Events are function members that simplify acting on object state changes (Albahari 2).
Concurrency • C# handles competition synchronization naturally by using monitors. • Cooperation synchronization must be provided with some form of semaphores • Data structures that consist of an integer and a task description queue. • If semaphores are used incorrectly, they can result in “errors that cannot be detected by the compiler, linker, or run-time system” (Sebesta 624). These potential undetected errors can severely impact reliability. • “C#’s support for concurrency is based on that of Java but is slightly more sophisticated” • “All .NET languages have the use of the generic concurrent data structures for stacks, queues, and bags, for which competition synchronization is implicit” (Sebesta 625).
Error and Event Handling • Built-in class: System.Exception. • Uses try, catch, and finally blocks. • The catch block executes when an error occurs in the try block. • The finally block executes no matter what when the other blocks are done. • Catch blocks are used to handle the exception or log the issue. Programmer specifies the exception to be handle in the catch block • Can catch the entire System.Exceptionclass, but rarely needed. • Potential recovery of the program regardless of the specific exception type • Planning to rethrow the exception after logging it • Last resort prior to termination of the program • Handle multiple exception types with multiple catch clauses • “Exceptions are relatively expensive to handle, taking hundreds of clock cycles” (Albahari 136).
Events • In .NET languages, “event handlers are registered by creating an EventHandlerobject and assigning it to the predefined delegate associated with the GUI object that can raise the event” (Sebesta 665). • After an event is detected, the code in the corresponding EventHandler is executed.
Readability • “Code like the person who maintains your code after you is a psychopath who knows where you sleep.” – Dr. Brenda Wilson
Readability .5 • Basic syntax feels intuitive • Abstracting common elements keeps code free of clutter. • User-defined structs and enumerations let programmers clearly name what may otherwise be confusing. • Many ways to do different things • Aliasing • Too many names for one thing can be really confusing. Pros Cons
Writability • Many different ways to accomplish a particular task • While not a direct language feature, Microsoft’s Visual Studio IDE makes writing code a breeze with Intellisense. • C# is very strict with its syntax, which can hinder beginners initially.
Reliability .5 • Strict type-checking • Implicit casting only if no loss of precision • Built-in Exception class • Any use of unsafe code has to be explicitly stated in the code and enabled in the complier • Aliases • Too many names is confusing and easily leads to errors. • Semaphores when used incorrectly • Difficult to detect any problem Pros Cons
Sources • http://www.codeguru.com/csharp/sample_chapter/article.php/c11387/Storing-Information-with-Variables-in-C.htm • Afana, Nadeem. Primitive, Reference, and Value Types. 12 September 2005. 30 September 2012 <http://www.codeproject.com/Articles/11212/Primitive-Reference-and-Value-Types>. • Albahari, Joseph, and Ben Albahari. C# 4.0 in a Nutshell. 4th Edition. Sebastopol: O'Reilly Media, Inc., 2010. • Clark, Dan. "Overview of Object-Oriented Programming." Clark, Dan. Beginning C# Object-Oriented Programming.Apress, 2011. 6. • Hejlsberg, Anders. The A-Z of Programming Languages: C# Naomi Hamilton. 1 October 2008. • Hejlsberg, Anders. The A-Z of Programming Languages: C# Naomi Hamilton. 1 October 2008. • Lippert, Eric. Not everything derives from object. 6 August 2009. 10 November 2012 <http://blogs.msdn.com/b/ericlippert/archive/2009/08/06/not-everything-derives-from-object.aspx>. • Microsoft Corporation. C# Operators (C# Reference). 2012. 30 September 2012 <http://msdn.microsoft.com/en-us/library/6a71f45d.aspx>. • —. Enumeration Types (C# Programming Guide). 2012. 30 9 2012 <http://msdn.microsoft.com/en-us/library/cc138362.aspx>. • —. for (C# Reference). 2012. 30 September 2012 <http://msdn.microsoft.com/en-us/library/ch45axte.aspx>. • —. foreach, in (C# Reference). 2012. 30 September 2012 <http://msdn.microsoft.com/en-us/library/ttw7t8t6.aspx>. • —. if-else (C# Reference). 2012. 30 September 2012 <http://msdn.microsoft.com/en-us/library/5011f09h.aspx>. • —. Reference Types (C# Reference). 2012. 30 September 2012 <http://msdn.microsoft.com/en-us/library/490f96s2.aspx>. • —. Struct (C# Reference). 2012. 30 September 2012 <http://msdn.microsoft.com/en-us/library/ah19swz4.aspx>. • —. switch (C# Reference). 2012. 30 September 2012 <http://msdn.microsoft.com/en-us/library/06tc147t.aspx>. • —. Types (C# Programming Guide). 2012. 30 September 2012 <http://msdn.microsoft.com/en-us/library/ms173104.aspx>. • —. Value Types (C# Reference). 30 September 2012 <http://msdn.microsoft.com/en-us/library/s1ax56ch.aspx>. • Sebesta, Robert W. Concepts of Programming Languages. 10th Edition. New York: Addison-Wesley, 2012. • Vrajitoru, Dana. Name, Scope, Binding. 2012. 30 September 2012 <http://www.cs.iusb.edu/~danav/teach/c311/c311_3_scope.html>.