0% found this document useful (0 votes)
2 views

c# notes

.NET is a Microsoft software platform that provides tools and libraries for developers to create applications across various operating systems. C# is a high-level programming language designed to work with .NET, offering features like object-oriented programming and type safety. The document also covers the concepts of literals and variables in C#, including their types, declaration, initialization, and best practices.

Uploaded by

pankaj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

c# notes

.NET is a Microsoft software platform that provides tools and libraries for developers to create applications across various operating systems. C# is a high-level programming language designed to work with .NET, offering features like object-oriented programming and type safety. The document also covers the concepts of literals and variables in C#, including their types, declaration, initialization, and best practices.

Uploaded by

pankaj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Confidential - Oracle Restricted

What is .NET

In simple words, .NET is a software platform developed by Microsoft that helps developers
create different types of applications more easily. It provides a collection of tools, libraries,
and a runtime environment to run programs smoothly.

Think of .NET as a big toolbox that includes:

• Libraries: Pre-built code to handle common tasks like data handling, web
development, and user interface design.

• Runtime (CLR): The "engine" that runs .NET programs, managing things like memory
and performance automatically.

• Cross-Platform Support: Modern versions allow you to create apps that work on
Windows, Linux, and macOS.

Developers use programming languages like C# with .NET to build apps for web, mobile,
desktop, and more.

What is C#?

• Programming Language: C# is a high-level programming language that combines


the efficiency and power of C++ with the ease of use of Visual Basic.

• Object-Oriented: C# supports object-oriented programming, which allows for


organizing code into objects that contain both data and methods.

• Type-Safe: Ensures that operations are performed safely and that data types are
used consistently.

• Feature-Rich: Includes advanced features such as garbage collection, exception


handling, and powerful language constructs like properties, events, and delegates.

• Versatile: Can be used for various types of applications, including web services,
cloud-based applications, and game development (using Unity).

How are C# and .NET Related?

• C# as a .NET Language: C# was specifically designed to work with the .NET


framework, leveraging its runtime (CLR) and libraries. While other languages like
VB.NET and F# can also be used with .NET, C# is the most commonly used and is
often seen as the flagship language for .NET development.

Confidential - Oracle Restricted


Confidential - Oracle Restricted

• Execution: When you write a C# program, it is compiled into Intermediate Language


(IL) code that runs on the CLR. The CLR converts IL code into machine code that can
be executed on a host operating system.

• Integration: C# interacts seamlessly with the .NET framework's extensive libraries,


making it easy for developers to build complex applications quickly. For example,
C# can use .NET libraries for tasks like file handling, web services, data access, and
user interface development.

4. Development Ecosystem

• Integrated Development Environment (IDE): Visual Studio and Visual Studio Code
are commonly used IDEs for C# development, offering rich features like debugging,
IntelliSense (code suggestion), and project management.

• ASP.NET: A part of the .NET platform used for developing web applications. With
ASP.NET Core, developers can build cross-platform, high-performance web
applications using C#.

• Xamarin: A .NET extension that enables C# to be used for mobile application


development on iOS and Android.

• Example of C# with .NET


• Here’s a simple C# program that runs on the .NET platform:

• using System;

• namespace ExampleApp
• {
• class Program
• {
• static void Main(string[] args)
• {
• Console.WriteLine("Hello, .NET and C#!"); // Outputs:
Hello, .NET and C#!
• }
• }
• }

Confidential - Oracle Restricted


Confidential - Oracle Restricted

Literals
Literals in programming refer to fixed values that appear directly in the source code. They
represent specific data values without the need for computation or manipulation. In .NET
languages like C#, literals are used to assign fixed values to variables and constants. Here’s
a detailed breakdown of literals in C#:

1. Definition of Literals

Literals are not variables but constant values written directly in the code. For example, 5,
3.14, 'A', and "Hello" are all literals.

2. Types of Literals in C#

Literals can be categorized based on the type of data they represent:

a. Integer Literals

These are whole numbers and can be written in different bases:

• Decimal (base 10): The most common form, e.g., 42, 0, -7.

• Hexadecimal (base 16): Starts with 0x or 0X, e.g., 0x1A, 0xFF.

• Binary (base 2): Starts with 0b or 0B, e.g., 0b1010, 0b1101.

Example:

csharp

int decimalLiteral = 42;

int hexLiteral = 0x2A; // Same as 42 in decimal

int binaryLiteral = 0b101010; // Also 42 in decimal

b. Floating-Point Literals

These represent real numbers with decimal points and can be of type float, double, or
decimal:

• Double (default): e.g., 3.14, 0.5.

• Float: Ends with f or F, e.g., 3.14f.

• Decimal: Ends with m or M, e.g., 3.14m.

Confidential - Oracle Restricted


Confidential - Oracle Restricted

Example:

csharp

double doubleLiteral = 3.14;

float floatLiteral = 2.5f;

decimal decimalLiteral = 7.89m;

c. Character Literals

Single characters enclosed in single quotes, e.g., 'A', '9', '#'.

• Unicode characters can be represented using \u followed by a four-digit


hexadecimal code, e.g., '\u0041' for A.

Example:

csharp

char letter = 'A';

char symbol = '#';

char unicodeChar = '\u0041'; // 'A'

d. String Literals

A sequence of characters enclosed in double quotes, e.g., "Hello, World!".

• Escape Sequences: Special characters represented with a backslash, e.g., "\n" for
a new line, "\t" for a tab.

• Verbatim String Literals: Prefixed with @ to ignore escape sequences, useful for
file paths or multi-line strings, e.g., @"C:\Users\Name".

Example:

csharp

string message = "Hello, World!";

string path = @"C:\MyFolder\MyFile.txt";

Confidential - Oracle Restricted


Confidential - Oracle Restricted

string multiline = @"This is a

multi-line string.";

e. Boolean Literals

Represent logical values and can only be true or false.

Example:

csharp

bool isActive = true;

bool hasErrors = false;

f. Null Literal

Represents the absence of a value for reference types, indicated by null.

Example:

csharp

string emptyString = null;

object obj = null;

3. Literal Suffixes

Some literals require suffixes to indicate their type:

• Integer suffixes: L or l for long, e.g., 42L.

• Floating-point suffixes: f or F for float, m or M for decimal.

• Double literals: By default, a floating-point number is treated as double.

Example:

csharp

long bigNumber = 1000000L;

float piApprox = 3.14f;

Confidential - Oracle Restricted


Confidential - Oracle Restricted

decimal money = 99.99m;

4. Special Literals

• Character Escape Sequences: Special characters can be used in strings and


characters.

o \n – New line

o \t – Tab

o \\ – Backslash

o \" – Double quote

o \' – Single quote

o \r – Carriage return

Example:

csharp

string withNewLine = "Hello\nWorld!";

• Verbatim Strings: Starts with @, which allows using multi-line text and ignores
escape sequences.

Example:

csharp

string filePath = @"C:\User\Documents\MyFile.txt";

5. Using Literals with Constants

Literals are often used to assign values to constants with the const keyword. This keyword
makes the value immutable.

Example:

csharp

const int daysInWeek = 7;

Confidential - Oracle Restricted


Confidential - Oracle Restricted

const string greeting = "Hello, World!";

What Are Variables in C#?

In C#, a variable is a named location in memory used to store data. Variables allow
programs to store, modify, and retrieve data during execution. Each variable has a specific
type that defines the kind of data it can hold, such as integers, characters, or strings.

1. Declaration and Initialization of Variables

• Declaration: Specifies the type of the variable and its name.

• Initialization: Assigns an initial value to the variable.

Syntax:

csharp

dataType variableName = initialValue;

Example:

csharp

int age = 25; // Declares an integer variable named 'age' and initializes it to 25

string name = "Alice"; // Declares a string variable named 'name' and initializes it to "Alice"

bool isStudent = true; // Declares a boolean variable named 'isStudent' and initializes it to
true

You can also declare a variable without initializing it:

csharp

int number;

number = 10; // Initialization after declaration

2. Types of Variables in C#

C# supports different types of variables, categorized into:

Confidential - Oracle Restricted


Confidential - Oracle Restricted

a. Primitive Data Types

• Integer Types: int, long, short, byte

• Floating-Point Types: float, double, decimal

• Character Type: char

• Boolean Type: bool

Example:

csharp

int count = 100;

double price = 19.99;

char letter = 'A';

bool isAvailable = false;

b. Reference Types

These variables store references to the memory location where the data is stored.
Common reference types include:

• Strings: A sequence of characters.

• Arrays: A collection of variables of the same type.

• Classes and Objects: Custom data structures.

• Interfaces.

Example:

csharp

string message = "Hello, World!";

int[] numbers = { 1, 2, 3, 4, 5 };

3. Variable Naming Rules and Conventions

• Must start with a letter or underscore.

Confidential - Oracle Restricted


Confidential - Oracle Restricted

• Cannot start with a number.

• Can contain letters, numbers, and underscores.

• C# is case-sensitive, so myVar and MyVar are different variables.

• Descriptive names are preferred to make the code easier to understand


(employeeSalary, totalScore).

Example:

csharp

int age; // Valid

string _name; // Valid

float $rate; // Invalid (special characters like $ are not allowed)

4. Variable Scope and Lifetime

• Scope: Refers to the region of the code where the variable is accessible.

o Local Variables: Declared within a method or block and can only be used
there.

o Global Variables: Declared at the class level and accessible throughout the
class.

• Lifetime: Refers to how long the variable exists in memory.

o Local Variables: Exist only during the execution of the block they are
declared in.

o Class-Level Variables: Exist as long as the instance of the class is active (for
instance variables) or for the lifetime of the application (for static variables).

Example:

csharp

class Program

Confidential - Oracle Restricted


Confidential - Oracle Restricted

int globalVar = 10; // Class-level variable

static void Main(string[] args)

int localVar = 5; // Local variable, exists only within Main method

Console.WriteLine(localVar);

5. Types of Variable Modifiers

Modifiers provide additional information about how variables behave:

• const: The value of the variable cannot be changed after it is initialized.

• readonly: The value can only be assigned during initialization or in a constructor.

• static: The variable belongs to the class itself, not an instance of the class.

Example:

csharp

const double PI = 3.14159; // Constant variable

static int counter = 0; // Static variable shared across all instances

readonly string id; // Read-only variable, assigned in a constructor

6. Default Values of Variables

Uninitialized variables of reference types default to null, while uninitialized value types
have specific default values:

• int: 0

• double: 0.0

• bool: false

• char: '\0' (null character)

Confidential - Oracle Restricted


Confidential - Oracle Restricted

Example:

csharp

int uninitializedInt; // Defaults to 0 if a field in a class

Console.WriteLine(uninitializedInt); // Prints 0 if uninitialized as a field

7. Var Keyword (Implicit Typing)

The var keyword allows the compiler to infer the type of the variable based on the assigned
value. It provides type safety but is more concise for the programmer.

Example:

csharp

var num = 42; // Inferred as int

var greeting = "Hello"; // Inferred as string

8. Nullable Types

Value types can be made nullable by adding a ? after the type, allowing them to store null
values. This is useful when you need to indicate that a variable might not have a value.

Example:

csharp

int? optionalValue = null;

if (optionalValue.HasValue)

Console.WriteLine(optionalValue.Value);

else

Console.WriteLine("Value is null");

Confidential - Oracle Restricted


Confidential - Oracle Restricted

9. Best Practices for Variables

• Use descriptive names for readability.

• Initialize variables to avoid unintentional behavior.

• Limit the scope of variables to the minimum necessary.

• Use const and readonly where applicable to prevent changes to critical values.

• Avoid global variables when possible to reduce dependencies and improve code
modularity.

Confidential - Oracle Restricted

You might also like