E FFECTIVE C# 50 Specific Ways to Improve Your C# Second Edition Bill Wagner محمد حسین سلطانی.

Slides:



Advertisements
Similar presentations
Generic programming in Java
Advertisements

CSE 1302 Lecture 8 Inheritance Richard Gesick Figures from Deitel, “Visual C#”, Pearson.
Defining classes and methods Recitation – 09/(25,26)/2008 CS 180 Department of Computer Science, Purdue University.
CS 4800 By Brandon Andrews.  Specifications  Goals  Applications  Design Steps  Testing.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Road Map Introduction to object oriented programming. Classes
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
CS102 Data Types in Java CS 102 Java’s Central Casting.
Advanced Object-Oriented Programming Features
Terms and Rules Professor Evan Korth New York University (All rights reserved)
What Is a Factory Pattern?.  Factories are classes that create or construct something.  In the case of object-oriented code languages, factories construct.
Types in programming languages What are types, and why do we need them? Types in programming languages1.
Java versus C# An introduction to C# and Visual Studio.
Apply Sub Procedures/Methods and User Defined Functions
Computer Programming and Basic Software Engineering 4. Basic Software Engineering 1 Writing a Good Program 4. Basic Software Engineering.
1 Using Classes Object-Oriented Programming Using C++ Second Edition 5.
Using Classes Object-Oriented Programming Using C++ Second Edition 5.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Chapter 12: Exception Handling
Lecture 8 Inheritance Richard Gesick. 2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To.
Chapter 8 More Object Concepts
Lecture 9 Polymorphism Richard Gesick.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
CIS 199 Test 01 Review. Computer Hardware  Central Processing Unit (CPU)  Brains  Operations performed here  Main Memory (RAM)  Scratchpad  Work.
Java Implementation: Part 3 Software Construction Lecture 8.
07 Coding Conventions. 2 Demonstrate Developing Local Variables Describe Separating Public and Private Members during Declaration Explore Using System.exit.
The Java Programming Language
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
Introduction to Exception Handling and Defensive Programming.
Modern Software Development Using C#.NET Chapter 5: More Advanced Class Construction.
Best Practices. Contents Bad Practices Good Practices.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
C# EMILEE KING. HISTORY OF C# In the late 1990’s Microsoft recognized the need to be able to develop applications that can run on multiple operating system.
Copyright © 2012 Pearson Education, Inc. Chapter 9 Classes and Multiform Projects.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Introduction to C#. Why C#? Develop on the Following Platforms ASP.NET Native Windows Windows 8 / 8.1 Windows Phone WPF Android (Xamarin) iOS (Xamarin)
Object Oriented Software Development
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
Computing with C# and the.NET Framework Chapter 2 C# Programming Basics ©2003, 2011 Art Gittleman.
Types in programming languages1 What are types, and why do we need them?
CIS 270—Application Development II Chapter 8—Classes and Objects: A Deeper Look.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Introduction to Object-Oriented Programming Lesson 2.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
Java Programming, Second Edition Chapter Twelve Advanced Inheritance Concepts.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
Module 13: Properties and Indexers. Overview Using Properties Using Indexers.
Winter 2006CISC121 - Prof. McLeod1 Last Time Reviewed class structure: –attributes –methods –(inner classes) Looked at the effects of the modifiers: –public.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
More Sophisticated Behavior
Jim Fawcett CSE681 – SW Modeling & Analysis Fall 2014
Inheritance and Polymorphism
Java Programming Language
Testing and Debugging.
Methods Attributes Method Modifiers ‘static’
Java Programming Language
Conditional Statements
Lecture 22 Inheritance Richard Gesick.
CIS 199 Final Review.
Binding 10: Binding Programming C# © 2003 DevelopMentor, Inc.
Presentation transcript:

E FFECTIVE C# 50 Specific Ways to Improve Your C# Second Edition Bill Wagner محمد حسین سلطانی

1- U SE P ROPERTIES I NSTEAD OF P UBLIC D ATA M EMBERS Properties enable you to create an interface that acts like data access but still has all the benefits of a method. Client code accesses properties as though they are accessing public fields. But the actual implementation uses methods The data binding classes in the.NET Framework support properties, not public data members. sample code: textBoxCity.DataBindings.Add("Text",address, "City");

Because properties are implemented with methods, adding multithreaded support is easier. Sample code: public class Customer { private object syncHandle = new object(); private string name; public string Name { get { lock (syncHandle) return name; } set { if (string.IsNullOrEmpty(value)) throw new ArgumentException("Name cannot be blank“,"Name"); lock (syncHandle) name = value; } // More Elided. }

Properties have all the language features of methods. Properties can be virtual: public class Customer { public virtual string Name { get; set; } You can extend properties to be abstract and define properties as part of an interface definition

Sample code: public interface INameValuePair { string Name { get; } T Value { get; set; } Anything you can do with member functions, you can do with properties If your type should contain indexed items as part of its interface, you can use indexers (which are parameterized properties)

public int this[int index] { get { return theValues[index]; } set { theValues[index] = value; } } // Accessing an indexer: int val = someObject[i]; Notice that all indexers are declared with the this keyword. You cannot name an indexer in C# Properties will not be faster than data member access, but they might not be any slower Get accessors should not have observable side effects. Set accessors do modify the state, and users should be able to see those changes All data members should be private, without exception

2- P REFER READONLY TO CONST C# has two different versions of constants: compile-time constants and runtime constants Compile-time constants are slightly faster, but far less flexible, than runtime constants. a slower, correct program is better than a faster, broken program // Compile time constant: public const int Millennium = 2000; // Runtime constant: public static readonly int ThisYear = 2004;

Compile-time constants can be declared inside methods.Read-only constants cannot be declared with method scope A compile-time constant is replaced with the value of that constant in your object code: if (myDateTime.Year == Millennium) compiled to the same IL as if you had written this: if (myDateTime.Year == 2000)

Compile-time constants can be used only for primitive types (built-in integral and floating-point types), enums, or strings. You cannot initialize a compile-time constant using the new operator Compile-time constants are limited to numbers and strings but runtime constants can be any type

I TEM 3: P REFER THE IS OR AS O PERATORS TO C ASTS The correct choice is to use the as operator whenever you can Comparing two types: Type 1: object o = Factory.GetObject(); // Version one: MyType t = o as MyType; if (t != null) { // work with t, it's a MyType. } else { // report the failure. }

Type 2: object o = Factory.GetObject(); // Version two: try { MyType t; t = (MyType)o; // work with T, it's a MyType. } catch (InvalidCastException) { // report the conversion failure. } the first version is simpler and easier to read. It does not have the try/catch clause. Using as, you simply check the returned reference against null. cast version must check null in addition to catching exceptions

The as operator does not work on value types. This statement won’t compile: object o = Factory.GetValue(); int i = o as int; // Does not compile. That’s because ints are value types and can never be null object o = Factory.GetValue(); int i = 0; try { i = (int)o; } catch (InvalidCastException) { i = 0; } You can use the is statement to remove the chance of exceptions or conversions:

object o = Factory.GetValue(); int i = 0; if (o is int) i = (int)o; The is operator should be used only when you cannot convert the type using as. The is operator always returns false for null arguments or not casted types If you’re about to convert a type using as, the is check is simply not necessary MyType t = null; if (o is MyType) t = o as MyType; foreach uses a cast operation to perform conversions from an object to the type used in the loop. foreach (MyType t in theCollection) t.DoStuff( ); Equals this code: IEnumerator it = theCollection.GetEnumerator(); while (it.MoveNext()) { MyType t = (MyType)it.Current; t.DoStuff(); }

foreach needs to use casts to support both value types and reference types The GetType() method gets the runtime type of an object Good object-oriented practice says that you should avoid converting types, but sometimes there are no alternatives. If you can’t avoid the conversions, use the language’s as and is operators to express your intent more clearly.

I TEM 4: U SE C ONDITIONAL A TTRIBUTES I NSTEAD OF # IF #if/#endif blocks have been used to produce different builds from the same source Use the Conditional attribute instead of #if/#endif blocks when you create conditional code blocks The StackTrace class gets the name of the calling method using Reflection The Debug.Assert method tests a condition and stops the program if that condition is false. The remaining parameters define messages The Conditional attribute tells the C# compiler that this method should be called only when the compiler detects the DEBUG environment variable.

[Conditional("DEBUG")] private void CheckState() { // same code as above } Whether the DEBUG environment variable is defined or not, the CheckState() method is compiled and delivered with the assembly The only cost is disk space. The CheckState() function does not get loaded into memory Multiple conditional attributes: [Conditional("DEBUG"), // in Debug or Trace Conditional("TRACE")] private void CheckState() #if ( VAR1 && VAR2 )// in Both cases #define BOTH #endif

Any method with a Conditional attribute must have a return type of void Any method marked with the Conditional attribute should not take any parameters

I TEM 5: A LWAYS P ROVIDE T O S TRING () You should write a reasonable version for all the clients of your class Every type that you create should provide a reasonable override of this method The System.Object version returns the fully qualified name of the type int[] list = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var test = new { Name = "Me", Numbers = from l in list select l }; Console.WriteLine(test); will display: { Name = Me, Numbers = System.Linq.Enumerable+WhereSelectArrayIterator`2 [System.Int32,System.Int32] }