Sayfalar

2 Şubat 2015 Pazartesi

C# Tips

I will give a few c# tips.

1) You can form objects via casting

class Tip1
    {
        public void Method1()
        {
            var entity = new Entity() { Name = "Mehmet", SureName = "Yoldaş" };
            var formedEntity = (FormedEntity)entity;
        }
    }
    public class FormedEntity
    {
        public string FullName { get; set; }
        public static explicit operator FormedEntity(Entity entity)
        {
            return new FormedEntity() { FullName = entity.Name + " " + entity.SureName };
        }
    }
    public class Entity
    {
        public string Name { get; set; }
        public string SureName { get; set; }


    }

2)  There is no nessesary null check operation when calling handler method. You could set empty delegate  to handler method.

    public delegate void MyEventHandler(object sender, int value);
        public event MyEventHandler Handle = delegate { };

        public void Method1() //use this method instead of Method2
        {
            Handle(this, -1);
        }

        public void Method2()
        {
       
            MyEventHandler handle = Handle;
            if (handle != null)
            {
                handle(this, -1);
            }

        }
3) If you do not use event args and sender information you should use directly method same as code below.

 public void method()
        {
            Button btn = new Button();
            btn.Click += btn_Click; //bad
            btn.Click += (o, a) => Save();//good
        }
        void Save()
        {

        }
        void btn_Click(object sender, EventArgs e)
        {
            Save();
        }


Hiç yorum yok:

Yorum Gönder