C# Pratik Kullanımlar & İpuçları #1 (Explicit Conversion)
12 Ağustos 2025 Yazarı yhackup 0

C# Pratik Kullanımlar & İpuçları #1 (Explicit Conversion)

Pratik bir type cast Kullanımı ile başlayalım.

        public class Model1
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Description { get; set; }
        }
       
        public class Model2
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Description { get; set; }
        }

propertyleri aynı olan iki tipi bir birine cast etmek için aşağıdaki gibi bir kullanım sağlayamazsınız IDE sizi uyaracaktır.

C# Pratik Kullanımlar & İpuçları #1 (Explicit Conversion)

Ya bu şekilde, tüm propertyleri her eşitlemeniz gerektiğinde tek tek tüm propertyleri eşitleyeceksiniz.

            Model1 model1 = new Model1
            {
                Id = 1,
                Name = "Test",
                Description = "Test açıklaması",
            };

            Model2 model2 = new Model2
            {
                Id= model1.Id,
                Name= model1.Name,
                Description = model1.Description,
            };

ya da explicit operator kullanabilirsiniz.

        public class Model1
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Description { get; set; }

            public static explicit operator Model2(Model1 model)
            {
                return new Model2
                {
                    Id = model.Id,
                    Name = model.Name,
                    Description = model.Description
                };
            }
        }

Sonrasında istediğiniz zaman bu şekilde atama sağlayabilirsiniz.

C# Pratik Kullanımlar & İpuçları #1 (Explicit Conversion)