19.02.2023 C#

Моя цель — изучить C# и поделиться с людьми тем, что я узнал. Я упомянул примеры с кодами комментариев.

Мы продолжим о C#

  • Логика ООП (объектно-ориентированное программирование)
  • CRUD-операции
  • Фрагменты
  • Стек и куча
  • Пустота
  • Метод коллекций (список)
  • Дженерики

Мы продолжим о C#. Также я буду давать информацию в блоке кода с помощью (// )

Сегодня я упомяну об объектно-ориентированном программировании (ООП).

ООП

Классы= классы разделены на 2 типа. У первого типа есть параметры, а у второго типа есть действия. Мы можем использовать эти типы в классе.

internal class Product //Entity 
    {
        //in this class which has just options.

        //but also we can use CRUD operations.It means Creat, Read, Update,Delete Operations.

        public int Id { get; set; }  // prop +tap+tap then it will be come.it means Snippet.
        public int CategoryId { get; set; }
        public string ProductName { get; set; }
        public double UnitPrice { get; set; }
        public int UnitInStock { get; set; }



    }

internal class ProductManager // when we see the MAnager Or Service Name,
      // it has a operation Class about product or something to CRUD Operation
    {
        public void Add() 
        { 

        }    
    }
internal class Program
    {
        static void Main(string[] args)
        {
            Product product1 = new Product();
            product1.Id = 1;
            product1.CategoryId = 2; //we can use this method to dataBase number.
            product1.ProductName = "Table";
            product1.UnitPrice = 500;
            product1.UnitInStock = 3;


Product product2=new Product{Id=2,CategoryId=5,UnitInStock=5,ProductName="Pencil",UnitPrice=35}; // Also We can write like this type

        }
    }

Я хочу дать трюки с кучей и стеком в классах.

//Also when we use the with heap it means with reference numbers. Let's see.
ProductManager productManager = new ProductManager();
int number = 25;
productManager.Add(number);  //we used the add funtion to change number.
Console.WriteLine(number);   // What is the number? After the change?                   
//ProductManager Class at the belows    //Answer=25 because we just the sending value of number, 
public void Add(int number  //that’s why number will not change.add function is worked just value 
        {
            number = 45;

        }   
               
product1.ProductName = "Table"; 
productManager.Dothat(product1); //Dothat is using product1 informartion with refenrance number.
Console.WriteLine(product1.ProductName);    // what is the ProductName At the screen?
//it is working in class at the below.                    //Answer=Camera
   public void Dothat(Product product)
 {  
                             //Because Dothat changed the product1 name in the reference number

            product.ProductName = "Camera";

        }
//Value Type=int,double,bool and etc
//Reference Type=Array,Class,Abstract Class,Interface etc.

Что такое методы Void?

Void — это методы, которые идут и что-то добавляют или делают, а затем завершают процесс. Когда нам не нужна дополнительная информация. Тогда мы используем Void.

Пример

public void Update(Product product)
        {
            Console.WriteLine(product.ProductName+" is Update");

        }


  public int Sum(int num1,int num2)
        {
            return num1 + num2;

        }  //why we are using both or why we are using void or sum2?

  public void Sum2(int num1, int num2)
        {
            Console.WriteLine(num1+num2);

        }


//İn main section

productManager.Sum2(3, 6); //when we use the this one we can not use another process just for going and doing we are using it.

            int SumOfResult = productManager.Sum(3, 6); //we use it as  a integer number.
// but when  we use the return then we can use the return value for another assigment or duty. 
            Console.WriteLine(2*SumOfResult);

//we can not use like this at the below.we can not defined the as a int.
// int result=productManager.Sum2(3, 6);

string[] names = new string[] { "Murat", "Enging", "Halil","Kerem" };

            Console.WriteLine(names[0]);
            Console.WriteLine(names[1]);
            Console.WriteLine(names[2]);
            Console.WriteLine(names[3]);
            //names[4] = "Ilker"; //we can not use it because we can not use 4 dont have memory.
            names = new string[5];  //but we can creat new names then we can use it
            names[4] = "ilker";         
            Console.WriteLine(names[4]); //we write the ilker then
            Console.WriteLine(names[2]); //but we cannot see the "Halil" because we created the new names then "Muret","Enging","halil" and "Kerem" are deleted
 //these informations is coming from data base normally.That's why when we want to change or add something, it is problem.In this case,We are using Collections.

Мы можем показать подобное.

У нас есть проблема. В этом случае мы используем метод списка.

List<string> names2 = new List<string> { "Engin", "Murat", "Kerem", "Halil" };
//when we used List.we Updated List which we can add easily and we can see the at screen.
            Console.WriteLine(names2[0]); 

            Console.WriteLine(names2[1]);
            Console.WriteLine(names2[2]);
            Console.WriteLine(names2[3]);

            names2.Add("Ilker");
            Console.WriteLine(names2[4]);
            Console.WriteLine(names2[1]);



Мы хотим использовать универсальный метод для списка, а также мы можем создать метод добавления с нашими кодами для логической функции Add().

static void Main(string[] args)
        {
            MyList<string> names = new MyList<string>(); //we select the which type will be to T also we defined the new reference.

        }
namespace GenericsIntro
{
    internal class MyList<T> //I will work with T.
    {

        T[] items;
        T[] temArray;

        public MyList() //constructor also when we new the MylistClass , Mylist will be working automaticly.
        {
            items = new T[0]; //we constructor the array and we defined the 0 element.

            

        }

        public void Add(T item) //t we can use any type in main class. it can be string or int etc.
        {
            
            tempArray= items; // temArray is defined the items reference number to not dissaper when we create new array length.
            //when we add more  add information to array then we have to use again to new and before value we defined the tempArray because items previous value or string will be dissapear.
            items = new T[items.Length+1]; //we create the new item reference numbers +1 to use value.it is dynamic.but we have problem about reference number. previousreference number will be dissapear.
            // now tempArray have to add the previous items to new items.
            for (int i = 0; i < tempArray.Length; i++)
            {
                items[i] = tempArray[i]; //previous items are added by tempArray to new items

            }

            items[items.Length-1] = item; //length how many items have it is start from 1,but we using inside the array numbers it is start from 0 that's why we started -1 value.and we added last item value to last item array.

        }

    }
}