08 Decision Making

Hello in this post we will know more about Decision Making so let’s get started 🙂

Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

Following is the general from of a typical decision making structure found in most of the programming languages:
Decision making

 

Continue reading

Advertisements

07 C# Operators

Hello everyone, last time in C# serious for beginners we talked about the Variables, Constants and Literals in C#
So, this time we are going to learn and know the C# Operators.

What is the Operator ?
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.

What are the types/kinds of these Operators ?

  •  Arithmetic Operators: (+, *, /, -, %)
    Arthimetic
    Arthimetic Ex

  •  Relational Operators: (==, !=, >, >=, <. <=)
    Relational

    and here’s an Example on the Relational Operators:
    Relational Ex
  •  Logical Operators: (&&. ||, !)
    Logical

    and here’s an Example on the Logical Operators:
    Logical Ex
  •  Bitwise Operators: (&, |, ^, <<, >>, ~)
    Bitwise

    and here’s an Example on the Bitwise Operators:
    Bitwise Ex
  •  Assignment Operators: (=, +=, -=, *= … etc)
    Assignment

    and here’s an Example on the Assignment Operators:
    Assignment Ex

Continue reading

بالعربى C#

خبر هــام لكل متابعى المدونة 🙂

ان شاء الله هيكون فى شرح لغة #C بالعربى الفترة القادمة ان شاء الله بجانب الشرح بالانجليزية … و ان شاء الله هيكون فى كمان فيديوهات توضيح أكتر بالعربى .. و ذلك بناءً على رغبة البعض 🙂

و لذا ابقى على اتصال لتعرف المزيد … 🙂

و انتظروا قريباً  #C بالعربى 🙂

و لكم التوفيق ان شاء الله 🙂

06 C# Variables

I apologize for that absence but let’s continue what we had started. 🙂

A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C# has a specific type, which determines the size and layout of the variable’s memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.

and here’s a link declares the basic value types provided in C#:
http://1drv.ms/1gtzAwV

Variable Definition in C#

Syntax for variable definition in C# is:

<data_type> <variable_list>;

Here, data_type must be a valid C# data type including char, int, float, double, or any user-defined data type, etc., and variable_list may consist of one or more identifier names separated by commas.
Some valid variable definitions are shown here:

int i, j, k;
char c, ch;
float f, salary;
double d;

Variable Initialization in C#
Variables are initialized (assigned a value) with an equal sign followed by a constant expression. The general form of initialization is:

variable_name = value;

Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as:

<data_type> <variable_name> = value;

Some examples are: 

int d = 3, f = 5;    /* initializing d and f. */
byte z = 22;         /* initializes z. */
double pi = 3.14159; /* declares an approximation of pi. */
char x = 'x';        /* the variable x has the value 'x'. */

It is a good programming practice to initialize variables properly, otherwise sometimes program would produce unexpected result. Try the following example, which makes use of various types of variables:

namespace VariableDefinition
 {
 class Program
 {
 static void Main(string[] args)
 {
 short a;
 int b ;
 double c;
 /* actual initialization */
 a = 10;
 b = 20;
 c = a + b;
 Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
 Console.ReadLine();
 }
 }
 }

 

Accepting Values from User:

The Console class in the System namespace provides a function ReadLine() for accepting input from the user and store it into a variable.
For example,

int num;
num = Convert.ToInt32(Console.ReadLIne());

The function Convert.ToInt32() converts the data entered by the user to int data type, because Console.ReadLine() accepts the data in string format.

C# Constants and Literals 

The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well.
The constants are treated just like regular variables except that their values cannot be modified after their definition.

Character Constants

Character literals are enclosed in single quotes, e.g., ‘x’ and can be stored in a simple variable of char type. A character literal can be a plain character (e.g., ‘x’), an escape sequence (e.g., ‘\t’), or a universal character (e.g., ‘\u02C0’).
There are certain characters in C# when they are preceded by a backslash they will have special meaning and they are used to represent like newline (\n) or tab (\t). Here, you have a list of some of such escape sequence codes:
http://1drv.ms/1gtCRMO

The following program demonstrates defining and using a constant in your program:

using System;
 namespace DeclaringConstants
 {
 class Program
 {
 static void Main(string[] args)
 {
 const double pi = 3.14159;
 // constant declaration double r;
 Console.WriteLine("Enter Radius: ");
 r = Convert.ToDouble(Console.ReadLine());
 double areaCircle = pi * r * r;
 Console.WriteLine("Radius: {0}, Area: {1}", r, areaCircle);
 Console.ReadLine();
 }
 }
 }

And now we have already know the Variables provided in C# and the Constants 
in the next time we will know the Operators in C#
So, Stay tuned for more 🙂
and feel free to contact me  any time. 

05 C# Data Types

And now we’re going to talk about C# Data Types and C# Type Conversion

In C#, variables are categorized into the following types:

  • Value types
  • Reference types
  • Pointer types

Value Types
Value type variables can be assigned a value directly. They are derived from the class System.ValueType. The value types directly contain data. Some examples are int, char, float, which stores numbers, alphabets, floating point numbers, respectively. When you declare an int type, the system allocates memory to store the value.

The kink below declares a table lists the available value types in C#
http://sdrv.ms/1fDrJML

To get the exact size of a type or a variable on a particular platform, you can use the sizeof method. The expression sizeof(type) yields the storage size of the object or type in bytes. Following is an example to get the size of int type on any machine:

using system;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataTypeApplication
  {
    class Program
      {
        static void Main(string[] args)
          {
            Console.WriteLine("Size of int: {0}", sizeof(int));
            Console.ReadLine();
          }
      }
  }

When the above code is compiled and executed, it produces the following result:
size

Reference Types
The reference types do not contain the actual data stored in a variable, but they contain a reference to the variables.
In other words, they refer to a memory location. Using more than one variable, the reference types can refer to a memory location. If the data in the memory location is changed by one of the variables, the other variable automatically reflects this change in value. Example of built-in reference types are: object, dynamic and string.

OBJECT TYPE
The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). Object is an alias for System.Object class. So object types can be assigned values of any other types, value types, reference types, predefined or user-defined types. However, before assigning values, it needs type conversion. When a value type is converted to object type, it is called boxing and on the other hand, when an object type is converted to a value type, it is called unboxing.

DYNAMIC TYPE
You can store any type of value in the dynamic data type variable. Type checking for these types of variables takes place at runtime. Dynamic types are similar to object types except that type checking for object type variables takes place at compile time, whereas that for the dynamic type variables takes place at run-time.

STRING TYPE
The String Type allows you to assign any string values to a variable. The string type is an alias for the System.String class. It is derived from object type.

 

Pointer Types
Pointer type variables store the memory address of another type. Pointers in C# have the same capabilities as in C or C++.
Syntax for declaring a pointer type is:

type*  identifier;

For Example:

char* cptr;
int* iptr;

And now we have already discussed the C# Data Types 🙂

So. it’s the time to know C# Type Conversions 

Type conversion is basically type casting or converting one type of data to another type. In C#, type casting has two forms:

  •  Implicit type conversion – these conversions are performed by C# in a type-safe manner. Examples are conversions from smaller to larger integral types and conversions from derived classes to base classes.
  •  Explicit type conversion – these conversions are done explicitly by users using the pre-defined functions. Explicit conversions require a cast operator.

The following example shows an explicit type conversion:

namespace TypeConversionApplication</pre>
{
class ExplicitConversion
{
static void Main(string[] args)
{
double d = 5673.74;
int i;
// cast double to int.
i = (int)d;
Console.WriteLine(i);
Console.ReadKey();
}
}
}

 

C# Type Conversion Methods
The link below declares the built-in type conversion methods:
http://sdrv.ms/1bwg2Fi

The following example converts various value types to string type:

namespace TypeConversionApplication
 {
     class StringConversion
     {
         static void Main(string[] args)
         {
             int i = 75;
             float f = 53.005f;
             double d = 2345.7652;
             bool b = true;
             Console.WriteLine(i.ToString());
             Console.WriteLine(f.ToString());
             Console.WriteLine(d.ToString());
             Console.WriteLine(b.ToString());
             Console.ReadKey(); 
         }
     }
 }

 

And now we have already finished our lesson 🙂
Next time we will talk about exciting topic so, Stay tuned 🙂
And if you need any help or support, Feel free to contact me 🙂

04 C# Syntax

Here’s the time to know what is the syntax of C#, as we know C# is an Object-Oriented programming language.In Object-Oriented Programming methodology, a program consists of various objects that interact with each other by means of actions. The actions that an object may take are called methods. Objects of the same kind are said to have the same type or, more often, are said to be in the same class. 

For example, let us consider a Rectangle object. It has attributes like length and width. Depending upon the design, it may need ways for accepting the values of these attributes, calculating area and display details.

Let us look at an implementation of a Rectangle class and discuss C# basic syntax, on the basis of our observations in it:

using system;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RectangleApplication
{
   class Rectangle
   {
      // member variables
      double length;
      double width;
      public void Acceptdetails()
      {
         length = 4.5;
         width = 3.5;
      }
      public double GetArea()
      {
         return length * width;
      }
      public void Display()
      {
         Console.WriteLine("Length: {0}", length);
         Console.WriteLine("Width: {0}", width);
         Console.WriteLine("Area: {0}", GetArea());
      }
   }
   class ExecuteRectangle
   {
        static void Main(string[] args)
        {
            Rectangle r = new Rectangle();
            r.Accepdetails();
            r.Display();
            Console.ReadLine();
        }
   }
}

The Using Keyword
The using keyword is used for including the namespaces in the program. A program can include multiple using statements. 

Comments in C#
Comments are used for explaining code. Compilers ignore the comment entries.
The multiline comments in C# programs start with /* and terminates with the characters */ as shown below:
/* This program demonstrates The basic syntax of C# programming Language */
Single-line comments are indicated by the ‘//’ symbol.
For example: //end class Rectangle.

Member Variables
Variables are attributes or data members of a class, used for storing data.In the preceding program, the Rectangle class has two member variables named length and width.

Member Functions
Functions are set of statements that perform a specific task. The member functions of a class are declared within the class. Our sample class Rectangle contains three member functions: AcceptDetails, GetArea and Display.

Instantiating a Class
In the preceding program, the class ExecuteRectangle is used as a class, which contains the Main() method and instantiates the Rectangle class.

Identifiers
An identifier is a name used to identify a class, variable, function, or any other user-defined item. The basic rules for naming classes in C# are as follows:

  •  A name must begin with a letter that could be followed by a sequence of letters, digits (0 – 9) or underscore. The first character in an identifier cannot be a digit.
  • It must not contain any embedded space or symbol like ? – +! @ # % ^ & * ( ) [ ] { } . ; : ” ‘ / and \. However, an underscore ( _ ) can be used.
  •  It should not be a C# keyword.

C# Keywords
Keywords are reserved words predefined to the C# compiler. These keywords cannot be used as identifiers; however, if you want to use these keywords as identifiers, you may prefix the keyword with the @ character.
In C#, some identifiers have special meaning in context of code, such as get and set, these are called contextual keywords.

And here’s a link which you will find a table of some Reserved Keywords and Contextual Keywords in C#:
http://sdrv.ms/1bfI1ft

And later we’re going to know the Data types and  and its Conversions.
My best wishes for you and thanks for your appreciated time 🙂
Stay tuned for more 🙂

03 C# Program Structure

Well, it’s the time to start the real technical sessions but before we start you will need to run your code and to run and execute  your programs you will have to Download and Install Visual C# Express 2010 or Visual Studio (any version)
and you can Download Visual C# Express 2010 from the link below:
http://www.visualstudio.com/downloads/download-visual-studio-vs

And to execute any C# program you need:

  1. Text editor
  2. Compiler
  3. and then, it will be executed.

So, let’s See and analyse a C# Hello World Example and take it as a reference.

Any C# Program basically consists of  the following:

  • Namespace Declaration
  • A Class (Methods and Attributes)
  • Main Method
  • Statements & Expressions
  • Comments (Optional)

So, let’s see the C# code of the Hello World Example:

using system;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorldApplication
{
 class HelloWorld
 {
  static void Main(string[] args)
  {
    /* my first program in C# */
   Console.WriteLine("Hello World");
   Console.ReadKey();
  }
 }
}

So, the output of this program when it’s executed will be :    Hello World

Time to analyse the code lines of that program.

  • The first line using system; –> the using keyword is used to include the System namespace in the program. A program generally has multiple using statements. 
  • The next line has the namespace declaration. A namespace is a collection of classes. The HelloWorldApplication namespace contains the class HelloWorld.
  • The next line has a class declaration, the class HelloWorld contains the data and method definitions that your program uses. Classes generally would contain more than one method. Methods define the behavior of the class. However, the HelloWorld class has only one method Main.
  • The next line defines the Main method, which is the entry point for all C# programs. The Main method states what the class will do when executed.
  • The next line /*…*/ will be ignored by the compiler and it has been put to add additional comments in the program (optional).
  •  The Main method specifies its behavior with the statement Console.WriteLine(“Hello World”);
    WriteLine
    is a method of the Console class defined in the System namespace. This statement causes the message “Hello, World!” to be displayed on the screen. 
  •  The last line Console.ReadKey(); is for the VS.NET Users. This makes the program wait for a key press and it prevents the screen from running and closing quickly when the program is launched from Visual Studio .NET.

And now you should know these important points:

  • C# is a Case Sensitive which means it distinguish between lower and capital letters.
  • All statements and expression must end with a semicolon (;).
  • The program execution starts at the Main method.

Time to Compile and Execute the program:
Kindly, Follow these steps 🙂

  1. Start Visual Studio.
  2. On the menu bar, choose File, New, Project.
  3. Choose Visual C# from templates, and then choose Windows.
  4. Choose Console Application.
  5. Specify a name for your project, and then choose the OK button.
  6. The new project appears in Solution Explorer.
  7. Write code above in the Code Editor.
  8. Click the Run button or the F5 key to run the project. A Command Prompt window appears that contains the line Hello World.

And to write this program but in Windows Form it will be different a little, Just follow these steps:

  1. Start Visual Studio.
  2. On the menu bar, choose File, New, Project or click (ctrl+shift+n).
  3. Choose Visual C# from templates, and then choose Windows.
  4. Choose Windows Form Application.
  5. Specify a name for your project, and then choose the OK button.
  6. This windows will be opened.
    1
  7. From the Toolbox find a Button Drag and Drop it in your Form that Appears or Double click it.
  8. Then, you will find the Button has been added to your form, from Properties Windows on your right you’ll find it and search Text and change it to Hello World and then, Double click the Button.
  9. Another window will appear, Write the following code and then press Start.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Hello");
        }
    }
}

And now we have already finished our first technical C# posts stay tuned for more and if you need any help just feel free to contact me 🙂
Thanks for your appreciated time 🙂