Pages

Showing posts with label C# Programming Overview. Show all posts
Showing posts with label C# Programming Overview. Show all posts

Monday, 15 June 2015

Variable

Variable

Variable is a name that represents data stored in memory during program execution, in the other words, it represents storage location that has a modifiable value.
C# provides four kind of variable like below:
Name Description
Local variable Holds temporary data within the scope of a method. Not a member of a type.
Field Holds data associated with a type or an instance of a type. Member of a type.
Parameter A temporary variable used to pass data from one method to another method.
Array element One member of a sequenced collection of (usually) homogeneous data items. Can be either local or a member of a type.

Let's take a look to the example:
using System;

namespace Program2
{
 class person
 {
  public string firstName;
  public string lastName;
  public ushort age;

  public void greet()
  {
   Console.WriteLine("Hello "+ firstName + " " + lastName);
  }

  public void talk(string words)
  {
   Console.WriteLine(firstName+" "+ lastName + " say "+ words);
  }
 }

 class Program
 {
  static void Main(string[] args)
  {
   person me=null;

   string personFirstName = "Yang";
   string personLastName = "Sopiana";
   ushort personAge = 29;
   string personSaidWord;

   me = new person();
   me.firstName = personFirstName;
   me.lastName = personLastName;
   me.age = personAge;
   me.greet();

   Console.Write("What Do you want to say:");
   personSaidWord = Console.ReadLine();

   me.talk(personSaidWord);
  }
 }
}
The above code will result:
Hello Yang Sopiana
What Do you want to say: Lets learn C#
Yang Sopiana say Lets learn C#

line :5-20 it's userdefined type definition to make our own-defined type named person
line :7-9 it's declaration of field firstName,lastName and age
[Type Name] [Variable Name]
line :11 & 16 it's method declaration
line :16 (string words) is declaration of parameter named words
line :18 This is the way to use variable value and show it into screen
line :26 Instantiation of userdifined type person to variable named me
line :28-30 Declaration local variable with initial value
[Type Name] [Variable Name] = [Value]
line :23-36 Asignment of me object's field
line :33 & 42 Method greet & talkinvocation.

Automatic Initialization

In previous code, we see some variables has initializer and some aren't.
Some kinds of variables are automatically set to default values if they are declared without an initializer, and others are not. Variables that are not automatically initialized to default values contain undefined values until the program assigns them a value.
Variable Stored In Auto-initialized Use
Local variables Stack or stack and heap No Used for local computation inside a function member
Class fields Heap Yes Members of a class
Struct fields Stack or heap Yes Members of a struct
Parameters Stack No Used for passing values into and out of a method
Array elements Heap Yes Members of an array

null and void

null indicates that a variable is set to nothing. Only reference types can be assigned the value null.

It is important to note that assigning the value null to a reference type is distinct from not assigning it at all. In other words, a variable that has been assigned null has still been set, and a variable with no assignment has not been set and therefore will likely cause a compile error if used prior to assignment.

Sometimes the C# syntax requires a data type to be specified but no data is passed. For example, if no return from a method is needed, C# allows the use of void to be specified as the data type instead. The use of void as the return type indicates that the method is not returning any data and tells the compiler not to expect a value. void is not a data type per se, but rather an identification of the fact that there is no data type.

Nullable Modifier

As I pointed out earlier, value types cannot be assigned null because, by definition, they can’t contain references, including references to nothing. However, this cause a problem in the real world, where values are missing or maybe unknown.
To declare variables that can store null you use the nullable modifier, ?.
int count = null;               //compile error because int can't be assigned to null
int? counter2 = null;   //can be compiled

Assigning null to value types is especially attractive in database programming. Frequently, value type columns in database tables allow nulls. Retrieving such columns and assigning them to corresponding fields within C# code is problematic, unless the fields can contain null as well. Fortunately, the nullable modifier is designed to handle such a scenario specifically.

Thursday, 11 June 2015

Type and Storage

What is The Type?

A type defines the blueprint for a value, in the other way we can say that type is a template for creating data structures.It isn’t the data structure itself, but it specifies the characteristics of objects constructed from the template.

A type is defined by the following elements:
  • A name
  • A data structure to contain its data members
  • Behaviors and constraints


Image above show us the structure of int and short.

Data Members and Function Members

There are two kinds of members in a type: data members and function members.
  • Data members store data that is relevant to the object of the class or to the class as a whole.
  • Function members execute code. Function members define how the type can act.

Figure below shows you int member:

Type Classification

A type can be classified based on how they defined and how they are stored in memory. From the way a type defined, we can separate to two groups, pre-defined and user-defined type. From how a type stored in memory, we can separate them in to value type and reference type.
Predifined Types simple Non-Numeric bool
char
Numeric Integer 8-Bit sbyte
byte
16-Bit short
ushort
32-Bit int
uint
64-Bit long
ulong
Floating Point decimal
float
double
object
string
Dynamic
Userdefined Types class Type
struct types
array types
enum types
delegate types
interface types

Predifined Types

Table below show Simple Predifined Type
Name Meaning Range .NET Framework Type Default Value
sbyte 8-bit signed integer -128 – 127 System.SByte 0
byte 8-bit unsigned integer 0 – 255 System.Byte 0
short 16-bit signed integer -32,768 – 32,767 System.Int16 0
ushort 16-bit unsigned integer 0 – 65,535 System.UInt16 0
int 32-bit signed integer -2,147,483,648 – 2,147,483,647 System.Int32 0
uint 32-bit unsigned integer 0 – 4,294,967,295 System.UInt32 0
long 64-bit signed integer -9,223,372,036,854,775,808 – 9,223,372,036,854,775,807 System.Int64 0
ulong 64-bit unsigned integer 0 – 18,446,744,073,709,551,615 System.UInt64 0
float Single-precision float 1.5×10-45–3.4×1038 System.Single 0.0f
double Double-precision float 5×10-324–1.7×10308 System.Double 0.0d
decimal Decimal value with 28-significant-digit precision ±1.0×1028–±7.9×1028 System.Decimal 0m
bool Boolean true, false System.Boolean false
char Unicode character U+0000–U+ffff System.Char \x0000
char Unicode character U+0000–U+ffff System.Char \x0000

Table below show Non-Simple Predifined Type
Name Meaning .NET Framework Type
object The base class from which all other types, including the simple types are derived System.Object
string A sequence of zero or more Unicode characters System.String
dynamic A type designed to be used with assemblies written in dynamic languages No corresponding .NET type

Userdefined Types

Besides predifined types, we can also create our own-defined class. C# provides six kinds of custom defined class, as below:
  • class types
  • struct types
  • array types
  • enum types
  • delegate types
  • interface types
Different from predifined types, userdefined type you need to create a type declaration, which includes the following information:
  • The kind of type you are creating
  • The name of the new type
  • A declaration (name and specification) of each of the type’s members—except for array and delegate types, which don’t have named members
For example, figure below shows you how to work with user defined class.

Value Type and Reference Type

Stack and Heap

Stack is a list of memory that acts as a last-in, first-out (LIFO) data structure. It stores several types of data:
  • The values of certain types of variables
  • The program’s current execution environment
  • Parameters passed to methods

Heap is an area of memory where chunks are allocated to store certain kinds of data objects. Unlike the stack, data can be stored and removed from the heap in any order.
Although you can store data in heap, but you can't delete them explicitly. Instead, the Garbage Collector (GC) will do it for you. When your program doesn't access the object in memory, the GC will delete and free the memory. This will free us from memory leaking problem.

Value Types and Reference Types

Types are divided into two categories: value types and reference types. Objects of these types are stored differently in memory.
  • Value types require only a single segment of memory, which stores the actual data.
  • Reference types require two segments of memory:
    • The first contains the actual data—and is always located in the heap.
    • The second is a reference that points to where the data is stored in the heap.
Category Description
Value types Simple types Signed integral: sbyte, short, int, long
Unsigned integral: byte, ushort, uint, ulong
Unicode characters: char
IEEE flating point: float, double
High-precision decimal: decimal
Boolean: bool
Enum types User-defied types of the form enum E {...}
Struct types User-defied types of the form struct S {...}
Nullable types Nullable types Extensions of all other value types with a null value
Reference types Class types Ultimate base class of all other types: object
Unicode strings: string
User-defied types of the form class C {...}
Interface types User-defied types of the form interface I {...}
Array types Single- and multi-dimensional; for example, int[] and int[,]
Delegate types User-defied types of the form e.g. delegate int D(...)

Identifier and Keywords

Identifier

Identifiers are character strings used to name things such as class, variables, methods, parameters and so on. You can create self-documenting identifiers by concatenating meaningful words into a single descriptive name, using uppercase and lowercase letters (e.g., FirstName, LastName, SocialSecurityNum, etc.). These are the identifiers in previous example program:
System Program1 Program Main args Console WriteLine Name ReadLine Read
There's some rule for defining identifier:
  • Identifiers are case-sensitive. For instance, the variable names myVariable and myvariable are different identifiers.
  • The alphabetic and underscore characters (a through z, A through Z, and _) are allowed at any position.
  • Digits are not allowed in the first position but are allowed everywhere else. Therefore: person1 is legal identifier, but 1Person is illegal
  • The @ character is allowed in the first position of an identifier but not at any other position. Although allowed, its use is generally discouraged. @FirstName is legal but First@name will be resulting compile error.

Commonly Used Identifier Naming Styles

Style Name Description Recommended Use Examples
Pascal casing Each word in the identifier is capitalized. Use for type names and member names visible outside the class. These include the names of the following: classes, methods, namespaces, properties, and public fields. FirstName,LastName
Camel casing Each word in the identifier, except the first, is capitalized. Use for local variable names and the names of formal parameters in method declarations. firstName,lastName
Camel case with leading underscore This is a camel-cased identifier that starts with an underscore. Use for the names of private and protected fields. _firstName,_lastName

Keywords

Keywords are the character string tokens used to define the C# language. The important thing about keyword is that they can not be used as identifier.
abstract const extern int out short typeof
as continue false interface override sizeof uint
base decimal finally internal params stackalloc ulong
bool default fixed is private static unchecked
break delegate float lock protected string unsafe
byte do for long public struc ushort
case double foreach namespace readonly switch using
catch else goto new ref this virtual
char enum if null return throw void
checked event implicit object sbyte true volatile
class explicit in operator sealed try while
Keywords cannot be used as variable names or any other form of identifier, unless prefaced with the @ character.

Contextual keywords are identifiers that act as keywords only in certain language constructs, this mean we can still use this as identifier.
add ascending async awai by descending dynamic
equals from get global group in into
join let on orderby partial remove select
set value var where yield

Main Method

Every C# program must have one class with a method called Main. In program shown previously, it was declared in a class called Program.
  • The starting point of execution of every C# program is at the first instruction in Main.
  • The name Main must be capitalized.
The simplest form of Main is the following:
static void Main( )
{
    Statements
}