C# Introduction

Variables, data types, conditional logic

TABLE OF CONTENTS

  • Primitive Data Types
    • Byte, Short, Int
    • Long, Float, Double
    • Boolean, Char
  • Declaring and Using Variables
    • Identifiers
    • Declaring Variables and Assigning Values
    • Literals
  • String
  • Object
  • Flow of control

C#

C# has some interesting features:
  • automatic type checking
  • automatic garbage collection
  • simplifies pointers, no directly accessible pointer to memory simplified network access
  • multi-threading!

HOW IT WORKS…!

  • The C# compiler specially targets .NET. Which means that all code written in C# will always runs within the .NET Framework.
  • Consequently, the architecture and methodologies of C# reflects the underlying methodologies of .NET

BASICS

  • It is designed to generate the code that targets .NET environment
  • C# syntax is very much similar to Java
  • C# is case sensitive and highly type safe language
  • C# builds on the lessons learned from C (High Performance), C++ (Object Oriented Structure), Java (Security) and Visual Basic (Rapid Development)
  • The C# compiler requires that any variable be initialized with some starting value before you refer that variable in an operation

OBJECT-ORIENTED

C# programs contain nothing but definitions and instantiations of classes
  • Everything is encapsulated in a class!

C# supports OOD

  • Polymorphism
  • Inheritance
  • Encapsulation
  • Abstraction

Namespaces

  • Namespace is a logical collection of Classes and their related Functions
  • .NET base classes are grouped into different groups through Namespaces
  • A single C# file can declare several Namespaces
  • The Namespaces are Implicitly public
  • Within a Namespace we can declare another Namespace, Class, Interface, Struct, Enum, Delegates
  • ou can alias a namespace with using.
  • A Namespace is referenced in a C# program by the “using” statement.

Declaring and Using Variables

PRIMITIVE TYPES AND VARIABLES

  • boolean, char, byte, short, int, long, float, double etc.
  • These basic (or primitive) types are the only types that are not objects (due to performance issues)
  • This means that you don’t use the new operator to create a primitive variable
  • Declaring primitive variables:

double gamma;
float middleValue = 1.3f;
int relativeValue, index = 2;
bool studentsLearning = true;
						

CONSTANTS

  • We use constants to declare local variable and fields
  • Constants have the following characteristics:
    • They must be initialized when they are declared and once value is assigned it can’t be overwritten.
    • The value of the constant must be computable at compile time. So runtime you can’t assign value for constant.
    • Constants are always implicitly static.

DATA TYPES

  • C# distinguishes between two categories of data types:
    • Value Types: These types stores its value directly into variable. Value types are stored in stack (static memory allocation ).
    • Reference Types: These types stores the reference to the value. These types are stored in managed heap (dynamic memory allocation).
  • In C#, all the primitive data types are value types where as class types are reference types.
    If you want to declare your own types as value type you should declare it as struct.

DATA TYPES (2)

  • C# has defined 15 predefined types, 13 are primitive types and 2 (object and string) are reference types
    • All types implicitly derived from the System.Object class.
    • Implements number of general purpose methods, includes, Equals(), GetHashCode(), GetType() and ToString().
  • The basic predefined are recognized by C# are not intrinsic to the language but are part of the .NET Framework. e.g. If you declare int in C#, what you are actually declaring is an instance of .NET struct System.Int32.

DECLARATIONS

  • 1.5f is a float value accurate to 7 decimal places
  • 1.5 is a double value accurate to 15-16 decimal places

int errValue = 1.2; // compiler error
bool isOK = 1; // compiler error
double fiveFourths = 5 / 4; // no error
double fiveFourthsAgain = 5.0 / 4.0; // no error
float ratio = 5.8f; //correct
     				

INITIALISATION

  • If no value is assigned prior to use, then the compiler will give an error
  • C# sets primitive variables to zero or false in the case of a boolean variable
  • All object references are initially set to null
  • An array of anything is an object
    • Set to null on declaration
    • Elements to zero, false or null on creation

ASSIGNING VALUES

  • Assigning of values to variables
    • Is done by using the = operator
  • All C# assignments are right associative
    • Variable identifier on the left
    • Value of the corresponding data type on the right

LITERALS

  • You may have noticed that the new keyword isn't used when initializing a variable of a primitive type.
  • Primitive types are special data types built into the language; they are not objects created from a class.
  • The C# language specification clearly defines "literal" - a literal is a source code representation of a value. Literals are things like true, 10, 5.7, 'c', "hello", null They are text that represents a specific fixed value.
  • Literals are represented directly in your code without requiring computation.

STRING

STRING (2)

  • Strings, which are widely used in C# programming
  • Are a sequence of characters.
  • Strings are objects.
  • The C# platform provides the String class to create and manipulate strings.
  • As with any other object, you can create String objects by using the new keyword and a constructor.

char[] helloArr = { 'h', 'e', 'l', 'l', 'o', '!' };
String helloStr = new String(helloArr);
Console.WriteLine(helloStr);
     				

STRING (3)

  • Note: The String class is immutable, so that once it is created a String object cannot be changed.
  • The String class has a number of methods, some of which will be discussed further, that appear to modify strings. Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation (can cause memory issues e.g. concatenating). Consider   StringBuilder.

STRING (4)


// Inefficient way of using immutable string
string output = "Some very very long text!";
for (int i = 0; i < output.Length; i++)
{
    output += i; //don't do this
}
return output;
					

OBJECT

OBJECT (2)

Let’s look at the concepts of Classes and Objects.
  • Object - have states and behaviors.
    • e.g. A dog has states - color, name, breed as well as behaviors -wagging, barking, eating.
    • An object is an instance of a class.
  • A software object's state is stored in fields and behavior is shown via methods. So in software development, methods operate on the internal state of an object and the object-to-object communication is done via methods.

OBJECT (3)

  • Class - can be defined as a template/blue print that describes the behaviors/states that object of its type support.
  • The Object Class is the root of the class hierarchy.
  • Every class has Object as a parent class. All objects, including arrays, implement the methods of this class.
  • The Object class is beneficial if you want to refer any object whose type you don't know.

FLOW OF CONTROL

FLOW OF CONTROL (2)

  • C# executes one statement after the other in the order they are written
  • Many C# statements are flow control statements:

IF – THE CONDITIONAL STATEMENT

  • The if statement evaluates an expression and if that evaluation is true then the specified action is taken
  • If the value of x is less than 10, make x equal to 10
  • It could have been written:
  • Or, alternatively:

RELATIONAL OPERATORS

  • == Equality (careful)
    • == is a reference comparison, i.e. both objects point to the same memory location
    • .Equals() is just a virtual method and behaves as such, so the overridden version will be used (which, for string type compares the contents).
  • != Not equal
  • >= Greater than or equal
  • <= Less than or equal
  • > Greater than
  • < Less than

RELATIONAL OPERATORS (2)


string s1 = "test";
string s2 = "test";
string s3 = "test1".Substring(0, 4);
object s4 = s3;
object.ReferenceEquals(s1, s2); s1 == s2; s1.Equals(s2);
object.ReferenceEquals(s1, s3); s1 == s3; s1.Equals(s3);
object.ReferenceEquals(s1, s4); s1 == s4; s1.Equals(s4);

// output
True True True
False True True
False False True
					

IF… ELSE

The if … else statement evaluates an expression and performs one action if that evaluation is true or a different action if it is false.

bool x = false;
bool oldX = true;
if (x != oldX)
{
    Console.WriteLine("x was changed!");
}
else
{
    Console.WriteLine("x was NOT changed!");
}
					

NESTED IF … ELSE


bool x = false;
bool oldX = true;
if (x != oldX)
{
   Console.WriteLine("x was changed!");
}
else
{
   if (x != false)
   {
       Console.WriteLine("x is true!");
   }
   else
   {
       Console.WriteLine("x is false!");
   }
   Console.WriteLine("x was NOT changed!");
}
					

ELSE IF

Useful for choosing between alternatives:

int n = 1;
int j = 2;
if (n == 1)
{
    // execute code block #1
}
else if (j == 2)
{
    // execute code block #2
}
else
{
    // if none of the above is true, execute code block #3
}
					

A WARNING…


int i = 1;
int j = 2;
if (i == j)
{
    if (i == 1)
        Console.WriteLine("Why no curly brace !?!");
}
else
    Console.WriteLine("Always use curly brace!");
							

SWITCH STATEMENT


int caseSwitch = 1;
switch (caseSwitch)
{
    case 1:
        Console.WriteLine("Case 1");
        break;
    case 2:
        Console.WriteLine("Case 2");
        break;
    default:
        Console.WriteLine("Default case");
        break;
}
						
office@e-dojo.it

EXERCISE

Problem 1: Setup Visual Studio IDE

Problem 2: Declare Variables

Declare 10 (ten) variables choosing for each of them the most appropriate of the types to represent the following values: 782130, -15, 48258542, 0, -10000, 782130, -95543, 962482, 2244230, 23474326891. Choose a large enough type for each number to ensure it will fit in it. Try to compile the code.

EXERCISE (2)

Problem 3: Float or Double


Which of the following values can be assigned to a variable of type float and which to a variable of type double: 34.567839023, 12.345, 8923.1234857, 3456.091? Write a program to assign the numbers in variables and print them to ensure no precision is lost.

Problem 4: Unicode Character

Declare a character variable and assign it with the symbol that has Unicode code 21 (decimal) using the \u00XX syntax, and then print it.

EXERCISE (3)

Problem 5: Boolean Variable

Declare a Boolean variable called isFemale and assign an appropriate value corresponding to your gender. Print it on the console.

Problem 6: Strings

Declare two string variables and assign them with Hello and World. Declare third variable and assign it with the concatenation of the first two variables.

Problem 7: Quotes in Strings

Write a program that outputs: The "use" of quotations causes difficulties!

EXERCISE (4)

Problem 8: Employee Data

A trading company wants to keep record of its employees. Each record would have the following characteristics:

  • First name
  • Last name
  • Age
  • Gender
  • Personal ID number (e.g. 8306112507)
  • Unique employee number (min is 15 digits)

Declare the variables needed to keep the information for a single employee using appropriate primitive data types. Use descriptive names. Print the data at the console.

EXERCISE (5)

Problem 9: Exchange Variable Values

Declare two integer variables a and b and assign them with 1 and 0 and after that exchange their values by using some programming logic. Print the variable values before and after the exchange.

Problem 10: Bank Account Data

A bank account has a holder name (first name, middle name and last name), available amount of money (balance), bank name, IBAN, 3 credit card numbers associated with the account. Declare the variables needed to keep the information for a single bank account using the appropriate data types and descriptive names.

EXERCISE (6)

Problem 11: Age checks

Write a program that prints if the user is older than 18, but younger than 80. Also we want to find out if somebody is younger than 18, but older than 16. You want to display a different message for the over 16s.