Syntax
Introduction to C# Syntax
C# is a statically typed, multi-paradigm language developed by Microsoft in 2000. It's primarily used for building Windows desktop applications and games. C# syntax is highly expressive, yet it is also simple and easy to learn.
Variables and Data Types
In C#, variables are declared before they are used. Data types are specified when we declare variables. Here is an example:
int num = 10;
string name = "John";
In the above example, int
and string
are data types, num
and name
are variables. num
is assigned with an integer value 10
and name
is assigned with a string value "John"
.
Control Structures
Control structures in C# include if
, else
, for
, while
, do..while
and switch
.
Here's an example of an if
statement:
int num = 10;
if (num > 5)
{
Console.WriteLine("Number is greater than 5");
}
In this example, if num
is greater than 5
, the message "Number is greater than 5" is printed to the console.
Functions
Functions in C# are blocks of code that perform particular tasks. Functions are declared using the void
keyword if they do not return a value. Functions that return a value specify the data type of the return value.
Here's an example of a function that adds two numbers:
static int Add(int a, int b)
{
return a + b;
}
In this example, Add
is a function that takes two integer parameters a
and b
, and returns the sum of these numbers.
Classes and Objects
In C#, we define our own types using classes. A class is a blueprint for creating objects (a particular data structure). An object is an instance of a class.
Here's an example of a class:
class Car
{
string color = "red";
void StartCar()
{
Console.WriteLine("Car Started");
}
}
In this example, Car
is a class with a string variable color
and a method StartCar()
.
Conclusion
This is a basic introduction to C# syntax. There is a lot more to explore in C#, including inheritance, interfaces, exceptions, and more. The best way to learn is by writing and running code. So, get your hands dirty and start coding!
Remember, practice is the key to mastering any programming language. Happy coding!