Sei sulla pagina 1di 72

C# VISUAL STUDIO

METHODS

• In C#, Method is a separate code block and that contain a series of


statements to perform a particular operations and methods must be declared
either in class or struct by specifying the required parameters.
EXAMPLE
KINDS OF METHODS

• Pure virtual method.


• Virtual method.
• Abstract method.
• Partial method.
• Extension method.
• Instance method (Non-static Method) Commonly used for C# Visual
Studio/Supports C#
• Static method.
STATIC AND NON-STATIC METHOD

C# supports two types of class methods;


• static methods, and;
• non static methods (instance method).
METHOD SIGNATURES

• Methods are declared in a class or struct by specifying the access level such
as public or private, optional modifiers such as abstract or sealed, the return
value, the name of the method, and any method parameters. These parts
together are the signature of the method.
• A return type of a method is not part of the signature of the method for the
purposes of method overloading. However, it is part of the signature of the
method when determining the compatibility between a delegate and the
method that it points to.
EXAMPLE
METHOD ACCESS

• Calling a method on an object is like accessing a field. After the object name,
add a period, the name of the method, and parentheses. Arguments are listed
within the parentheses, and are separated by commas. The methods of
the Motorcycleclass can therefore be called as in the following example:
METHOD PARAMETERS VS. ARGUMENTS

• he method definition specifies the names and types of any parameters that
are required. When calling code calls the method, it provides concrete values
called arguments for each parameter. The arguments must be compatible with
the parameter type but the argument name (if any) used in the calling code
does not have to be the same as the parameter named defined in the method.
EXAMPLE
PASSING BY REFERENCE VS. PASSING BY VALUE
• By default, when a value type is passed to a method, a copy is passed instead of
the object itself. Therefore, changes to the argument have no effect on the original
copy in the calling method. You can pass a value-type by reference by using the ref
keyword. For more information, see Passing Value-Type Parameters. For a list of
built-in value types, see Value Types Table.
• When an object of a reference type is passed to a method, a reference to the object
is passed. That is, the method receives not the object itself but an argument that
indicates the location of the object. If you change a member of the object by using
this reference, the change is reflected in the argument in the calling method, even if
you pass the object by value.
EXAMPLE
RETURN VALUES

• Methods can return a value to the caller. If the return type, the type listed
before the method name, is not void, the method can return the value by using
the return keyword. A statement with the return keyword followed by a value
that matches the return type will return that value to the method caller.
• The return keyword also stops the execution of the method. If the return type
is void, a return statement without a value is still useful to stop the execution of
the method. Without the return keyword, the method will stop executing when
it reaches the end of the code block. Methods with a non-void return type are
required to use the return keyword to return a value.
• To use a value returned from a method, the calling method can use the method
call itself anywhere a value of the same type would be sufficient.
• You can also assign the return value to a variable.
• Using a local variable, in this case, result, to store a value is optional. It may
help the readability of the code, or it may be necessary if you need to store
the original value of the argument for the entire scope of the method.
• To use a value returned by reference from a method, you must declare a ref
local variable if you intend to modify its value. For example, if
the Planet.GetEstimatedDistance method returns a Double value by reference,
you can define it as a ref local variable with code like the following:
• Returning a multi-dimensional array from a method, M, that modifies the
array's contents is not necessary if the calling function passed the array
into M. You may return the resulting array from M for good style or functional
flow of values, but it is not necessary because C# passes all reference types
by value, and the value of an array reference is the pointer to the array. In
the method M, any changes to the array's contents are observable by any
code that has a reference to the array,
EXAMPLE
ASYNC METHODS
• Using the async feature, you can invoke asynchronous methods without using
explicit callbacks or manually splitting your code across multiple methods or
lambda expressions.
• If you mark a method with the async modifier, you can use the await operator
in the method. When control reaches an await expression in the async method,
control returns to the caller, and progress in the method is suspended until the
awaited task completes. When the task is complete, execution can resume in
the method.
• An async method can have a return type of Task<TResult>, Task, or void. The
void return type is used primarily to define event handlers, where a void
return type is required. An async method that returns void can't be awaited,
and the caller of a void-returning method can't catch exceptions that the
method throws.
EXAMPLE
EXPRESSION BODY DEFINITIONS

• It is common to have method definitions that simply return immediately with


the result of an expression, or that have a single statement as the body of the
method.
STATIC METHOD

• A static method in C# is a method that keeps only one copy of the method at
the Type level, not the object level. That means, all instances of the class share
the same copy of the method and its data. The last updated value of the
method is shared among all objects of that Type.
• You can access static methods by class name.
• You can put static method in static or non-static classes.
• Static often improves performance.
• Static classes cannot be instantiated.
• Static classes can only have static methods.
• Static methods must be called on the class itself, not on the instances of the
class.
EXAMPLE #1
EXAMPLE #2
NON-STATIC (INSTANCE) METHOD

• belong to each instance created from the class.


• are methods for the object, the instance of your class, which reflect a
functionality for that type.
• Non-static (“regular”) classes can be instantiated.
• Non-static classes can have instance methods and static methods.
• Instance methods must be called on the instances of the class, not the class
itself.
EXAMPLE #1
EXAMPLE #2
DIFFERENCE OF STATIC AND NON-STATIC

• A static method belongs to the class and a non-static method belongs to an


object of a class. ... A static method is shared by all instances of the class.
Whenever a method is called in C++/Java/C#, an implicit argument (the
'this' reference) is passed along with/without the other parameters.
NAMESPACES
• Namespaces are used in C# to organize and provide a level of separation of codes.
They can be considered as a container which consists of other namespaces, classes,
etc.
• Namespaces are not mandatory in a C# program, but they do play an important
role in writing cleaner codes and managing larger projects.
• The concept of namespace is similar in C#. It helps us to organize different members
by putting related members in the same namespace.
• Namespace also solves the problem of naming conflict. Two or more classes when
put into different namespaces can have same name.
• Namespaces are heavily used in C# programming in two ways. First, the .NET
Framework uses namespaces to organize its many classes, as follows:

• System is a namespace and Console is a class in that namespace.


The using keyword can be used so that the complete name is not required, as
in the following example:
• Second, declaring your own namespaces can help you control the scope of
class and method names in larger programming projects. Use
the namespace keyword to declare a namespace, as in the following
example:
NAMESPACES OVERVIEW

Namespaces have the following properties:


• They organize large code projects.
• They are delimited by using the . operator.
• The using directive obviates the requirement to specify the name of the
namespace for every class.
• The global namespace is the "root" namespace: global::System will always
refer to the .NET System namespace.
EXAMPLE
CLASSES

• A class normally consists of Methods, Fields and Properties.


• Every class has a constructor, which is called automatically any time an
instance of a class is created. The purpose of constructors is to initialize class
members when an instance of the class is created. Constructors do not have
return values and always have the same name as the class.
EXAMPLE
REFERENCE TYPES

• A type that is defined as a class is a reference type. At run time, when you
declare a variable of a reference type, the variable contains the
value null until you explicitly create an instance of the class by using
the new operator, or assign it an object of a compatible type that may have
been created elsewhere, as shown in the following example:
EXAMPLE
DECLARING CLASSES

• Classes are declared by using the class keyword followed by a unique


identifier, as shown in the following example:
CREATING OBJECTS

• A class defines a type of object, but it is not an object itself. An object is a


concrete entity based on a class, and is sometimes referred to as an instance
of a class.
• Objects can be created by using the new keyword followed by the name of
the class that the object will be based on, like this:
CLASS INHERITANCE

• Classes fully support inheritance, a fundamental characteristic of object-


oriented programming.
• Inheritance is accomplished by using a derivation, which means a class is
declared by using a base class from which it inherits data and behavior. A
base class is specified by appending a colon and the name of the base class
following the derived class name, like this:
EXAMPLE
PUBLIC CLASS EXAMPLE
CONSTRUCTOR

• The purpose of constructors is to initialize class members when an instance of


the class is created.
• Constructors enable the programmer to set default values, limit instantiation,
and write code that is flexible and easy to read.
EXAMPLE
EXAMPLE
CONSTRUCTOR SYNTAX
• A constructor is a method whose name is the same as the name of its type. Its
method signature includes only the method name and its parameter list; it
does not include a return type. The following example shows the constructor
for a class named Person.
• If a constructor can be implemented as a single statement, you can use
an expression body definition. The following example defines a Location class
whose constructor has a single string parameter named name. The expression
body definition assigns the argument to the locationName field.
PROPERTIES

• A property is a member that provides a flexible mechanism to read, write, or


compute the value of a private field. Properties can be used as if they are
public data members, but they are actually special methods called accessors.
This enables data to be accessed easily and still helps promote the safety and
flexibility of methods.
EXAMPLE
PROPERTIES OVERVIEW
• Properties enable a class to expose a public way of getting and setting values, while
hiding implementation or verification code.
• A get property accessor is used to return the property value, and a set property accessor
is used to assign a new value. These accessors can have different access levels. For more
information, see Restricting Accessor Accessibility.
• The value keyword is used to define the value being assigned by the set accessor.
• Properties can be read-write (they have both a get and a set accessor), read-only (they
have a get accessor but no set accessor), or write-only (they have a set accessor, but
no get accessor). Write-only properties are rare and are most commonly used to restrict
access to sensitive data.
• Simple properties that require no custom accessor code can be implemented either as
expression body definitions or as auto-implemented properties.
PROPERTIES WITH BACKING FIELDS

• One basic pattern for implementing a property involves using a private


backing field for setting and retrieving the property value. The get accessor
returns the value of the private field, and the set accessor may perform some
data validation before assigning a value to the private field. Both accessors
may also perform some conversion or computation on the data before it is
stored or returned.
EXAMPLE
AUTO-IMPLEMENTED PROPERTIES

• In some cases, property get and set accessors just assign a value to or retrieve
a value from a backing field without including any additional logic. By using
auto-implemented properties, you can simplify your code while having the C#
compiler transparently provide the backing field for you.
• If a property has both a get and a set accessor, both must be auto-
implemented. You define an auto-implemented property by using
the get and set keywords without providing any implementation.
NAMING CONVENTION
• In short examples that do not include using directives, use namespace
qualifications. If you know that a namespace is imported by default in a
project, you do not have to fully qualify the names from that namespace.
Qualified names can be broken after a dot (.) if they are too long for a single
line, as shown in the following example.
WORD CHOICE
• ✓ DO choose easily readable identifier names.
• For example, a property named HorizontalAlignment is more English-readable
than AlignmentHorizontal.
• ✓ DO favor readability over brevity.
• The property name CanScrollHorizontally is better than ScrollableX (an obscure
reference to the X-axis).
• X DO NOT use underscores, hyphens, or any other nonalphanumeric characters.
• X DO NOT use Hungarian notation.
• X AVOID using identifiers that conflict with keywords of widely used programming
languages.
USING ABBREVIATIONS AND ACRONYMS
• X DO NOT use abbreviations or contractions as part of identifier names.
• For example, use GetWindow rather than GetWin.
• X DO NOT use any acronyms that are not widely accepted, and even if they
are, only when necessary.
AVOIDING LANGUAGE SPECIFIC NAMES
• ✓ DO use semantically interesting names rather than language-specific
keywords for type names.
• For example, GetLength is a better name than GetInt.
• ✓ DO use a generic CLR type name, rather than a language-specific name, in
the rare cases when an identifier has no semantic meaning beyond its type.
For example, a method converting to Int64 should be named ToInt64,
not ToLong (because Int64 is a CLR name for the C#-specific alias long). The
following table presents several base data types using the CLR type names (as
well as the corresponding type names for C#, Visual Basic, and C++).
TERMINOLOGY
• Camel Case (camelCase): In this the first letter of word always in small letter
and after that each word with capital letter.
• Pascal Case (PascalCase): In this the first letter of every word is in capital
letter.
• Underscore Prefix (_underScore): For underscore ( __ ), the word after _ use
camelCase terminology.
NATIVE DATA TYPE
• Always use native datatype instead of .NET CTS type. For example,
use int instead of Int32or Int64.


CLASS
• Always use PascalCase for class names. Try to use noun or noun phrase for
class name.
METHODS
• Always use PascalCase for method names. Use maximum 7 parameter for a method.

ARGUMENTS AND LOCAL VARIABLE


• Always use camelCase with method arguments and local variables. Don't use
Hungarian notation for variables.
PROPERTY
• Use PascalCase for property. Never use Get and Set as prefix with property
name.
INTERFACE
• Always use letter "I" as prefix with name of interface. After letter I, use
PascalCase.
PRIVATE MEMBER VARIABLE
• Always try to use camelCase terminology prefix with underscore ( _ ).

PUBLIC MEMBER VARIABLE


• Always use PascalCase for public member variable.

MEMBER VARIABLE
• Declare member variable at the top of the class, If class has static member
then it will come at the top most and after that other member variable.
ENUM
• Always use singular noun to define enum.

Potrebbero piacerti anche