Console.WriteLine("Hello World!");
//def
static int MyMethod(int x)
{
return 5 + x;
}
//def call in Main
static void Main(string[] args)
{
Console.WriteLine(MyMethod(3));
}
// Outputs 8 (5 + 3)
static int PlusMethodInt(int x, int y)
{
return x + y;
}
static double PlusMethodDouble(double x, double y)
{
return x + y;
}
static void Main(string[] args)
{
int myNum1 = PlusMethodInt(8, 5);
double myNum2 = PlusMethodDouble(4.3, 6.26);
Console.WriteLine("Int: " + myNum1);
Console.WriteLine("Double: " + myNum2);
}
bool isCSharpFun = true;
bool isFishTasty = false;
Console.WriteLine(isCSharpFun); // Outputs True
Console.WriteLine(isFishTasty); // Outputs False
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int
Console.WriteLine(myDouble); // Outputs 9.78
Console.WriteLine(myInt); // Outputs 9
// Type your username and press enter
Console.WriteLine("Enter username:");
// Create a string variable and get user input from the keyboard and store it in the variable
string userName = Console.ReadLine();
// Print the value of the variable (userName), which will display the input value
Console.WriteLine("Username is: " + userName);
// Create a Car class
class Car
{
public string model; // Create a field without further info
// Create a class constructor for the Car class
public Car()
{
model = "Mustang"; // Set the initial value for model
}
static void Main(string[] args)
{
Car Ford = new Car(); // Create an object of the Car Class (this will call the constructor)
Console.WriteLine(Ford.model); // Print the value of model
}
}
// Outputs "Mustang"
Console.WriteLine("Enter your age:");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your age is: " + age);
Абстрагирование / Абстракция в программировании — это способ снизить сложность и повысить эффективность проектирования и реализации программного обеспечения за счёт сокрытия технической сложности за более простым вариантом.

Инкапсуляция – языковой механизм ограничения доступа к определённым компонентам объекта а так-же языковая конструкция, способствующая объединению данных с методами (или другими функциями), обрабатывающими эти данные.

Полиморфизм – возможность объектов с одинаковой спецификацией иметь различную реализацию.

Наследование – возможность позволяющая описать новый класс на основе уже существующего (родительского), при этом свойства и функциональность родительского класса заимствуются новым классом.

Override – Модификатор override
требуется для расширения или изменения абстрактной или виртуальной реализации унаследованного метода, свойства, индексатора или события.
В этом примере определяется базовый класс с именем Employee
и производный класс с именем SalesEmployee
. Класс SalesEmployee
включает дополнительное поле salesbonus
, для использования которого переопределяется метод CalculatePay
.
class TestOverride
{
public class Employee
{
public string Name { get; }
// Basepay is defined as protected, so that it may be
// accessed only by this class and derived classes.
protected decimal _basepay;
// Constructor to set the name and basepay values.
public Employee(string name, decimal basepay)
{
Name = name;
_basepay = basepay;
}
// Declared virtual so it can be overridden.
public virtual decimal CalculatePay()
{
return _basepay;
}
}
// Derive a new class from Employee.
public class SalesEmployee : Employee
{
// New field that will affect the base pay.
private decimal _salesbonus;
// The constructor calls the base-class version, and
// initializes the salesbonus field.
public SalesEmployee(string name, decimal basepay, decimal salesbonus)
: base(name, basepay)
{
_salesbonus = salesbonus;
}
// Override the CalculatePay method
// to take bonus into account.
public override decimal CalculatePay()
{
return _basepay + _salesbonus;
}
}
static void Main()
{
// Create some new employees.
var employee1 = new SalesEmployee("Alice", 1000, 500);
var employee2 = new Employee("Bob", 1200);
Console.WriteLine($"Employee1 {employee1.Name} earned: {employee1.CalculatePay()}");
Console.WriteLine($"Employee2 {employee2.Name} earned: {employee2.CalculatePay()}");
}
}
/*
Output:
Employee1 Alice earned: 1500
Employee2 Bob earned: 1200
*/
Virtual – Ключевое слово virtual
используется для изменения объявлений методов, свойств, индексаторов и событий и разрешения их переопределения в производном классе. Например, этот метод может быть переопределен любым наследующим его классом:
public virtual double Area()
{
return x * y;
}