Programming techniques

about every things that i''m learning and want learn to other people

Programming techniques

about every things that i''m learning and want learn to other people

Type safety

Type safety means that the compiler will validate types while compiling, and throw an error if you try to assign the wrong type to a variable.

Some simple examples:

// Fails, Trying to put an integer in a string
String one = 1;
// Also fails.
int foo = "bar";

This also applies to method arguments, since you are passing explicit types to them:

int AddTwoNumbers(int a, int b)
{
    return a + b;
}

If I tried to call that using:

int Sum = AddTwoNumbers(5, "5");

The compiler would throw an error, because I am passing a string ("5"), and it is expecting an integer.

In a loosely typed language, such as javascript, I can do the following:

function AddTwoNumbers(a, b)
{
    return a + b;
}

if I call it like this:

Sum = AddTwoNumbers(5, "5");

Javascript automaticly converts the 5 to a string, and returns "55". This is due to javascript using the + sign for string concatenation. To make it type-aware, you would need to do something like:

function AddTwoNumbers(a, b)
{
    return Number(a) + Number(b);
}

Or, possibly:

function AddOnlyTwoNumbers(a, b)
{
    if (isNaN(a) || isNaN(b))
        return false;
    return Number(a) + Number(b);
}

if I call it like this:

Sum = AddTwoNumbers(5, " dogs");

Javascript automatically converts the 5 to a string, and appends them, to return "5 dogs".

Not all dynamic languages are as forgiving as javascript (In fact a dynamic language does not implicity imply a loose typed language (see Python)), some of them will actually give you a runtime error on invalid type casting.

While its convenient, it opens you up to a lot of errors that can be easily missed, and only identified by testing the running program. Personally, I prefer to have my compiler tell me if I made that mistake.

Now, back to C#...

C# supports a language feature called covariance, this basically means that you can substitute a base type for a child type and not cause an error, for example:

 public class Foo : Bar
 {
 }

Here, I created a new class (Foo) that subclasses Bar. I can now create a method:

 void DoSomething(Bar myBar)

And call it using either a Foo, or a Bar as an argument, both will work without causing an error. This works because C# knows that any child class of Bar will implement the interface of Bar.

However, you cannot do the inverse:

void DoSomething(Foo myFoo)

In this situation, I cannot pass Bar to this method, because the compiler does not know that Bar implements Foo's interface. This is because a child class can (and usually will) be much different than the parent class.



http://stackoverflow.com/questions/260626/what-is-type-safe

ایجاد متد با پارامتر های نا معیین

چگونه می توان زمان call کردن یک متد پارامتر های ان را مشخص کرد و یا به یک متد یه تعداد دلخواه در زمان فراخوانی پارامتر ارسال کرد ؟Param

public static void UseParams(params int[] list)

چگونه می توان به یک متد که دارای پارامتر می باشد پارامتر با type دلخواه به آن ارسال کرد ؟\پارامتر از نوع Object

public static void UseObject(object obj)

چگونه می توان یک متد با Type و تعداد پارامتر های نا مشخص ایجاد تا بتوان در زمان callکردن آن ها را تعیین کرد ؟

public static void UseParams2(params object[] list)

 

 

 

// cs_params.cs

using System;

public class MyClass

{

 

   public static void UseParams(params int[] list)

   {

      for ( int i = 0 ; i < list.Length ; i++ )

         Console.WriteLine(list[i]);

      Console.WriteLine();

   }

 

   public static void UseParams2(params object[] list)

   {

      for ( int i = 0 ; i < list.Length ; i++ )

         Console.WriteLine(list[i]);

      Console.WriteLine();

   }

 

   public static void Main()

   {

      UseParams(1, 2, 3);

      UseParams2(1, 'a', "test");

 

      int[] myarray = new int[3] {10,11,12};

      UseParams(myarray);

   }

}

 

با تشکر از اطلاعات همکارم آقای گرجی


 

http://msdn.microsoft.com/en-us/library/w5zay9db(v=vs.71).aspx

چگونه می توان یک تابع را به هر نوع کلاسی اضافه کرد ؟

 

Extension Methods

·         آیا به کلاس های  sealed می توان تابعی افزود ؟

·         چگونه می توان یک تابع را به هر نوع  کلاسی اضافه کرد ؟

·         آیا می توان یک کلاس را در خارج از بدنه کلاس تعمیم و یا این کار را در فضای نام همان کلاس یا خارج از آن انجام داد؟

 جواب این پرسش ها در Extension Methods می باشد

قبل از C# 3.0  فقط می‌شد یک کلاس را از طریق ارث‌بری از آن توسعه داد اما حالا اکنون میتوان با متد های توسعه این کار را انجام داد

توابع تعمیم یافته به اعضاء خصوصی کلاسی که تعمیم می‌یابد، دسترسی ندارند.

 شکل کلی توابع تعمیم یافته :

 

public static class ExtendingClassName

{

public static ReturnType MethodName(this   ExtendedMethod arg)

{

//دستورات درون متد

Return ReturnType;

}

}

 

 توجه کنید که:

1.       کلاس توسعه‌دهنده و تابع توسه‌دهنده باید استاتیک باشند.

2.       در داخل آرگومان تابع، کلمه کلیدی this  استفاده می‌‎‎شود.

3.       بعد از this عنوان کلاسی که قصد توسعه آن را داریم، ذکر می‌کنیم.

4.       در هرجا که خواستیم از قابلیت تعمیم داده شده استفاده کنیم باید فضای نام مربوط به آن را ذکر کنیم.

5.       با کلمه کلیدی static  نمیتوان کلاسی با متدهایvirtual  ، abstract  و override را توسعه داد. 

 

 public static class ExtendingString

    {

        public static string AddPrefix(this   string arg, string prefix)

        {

            return String.FormatFormat("{0}{1}", prefix, arg);

        }

    }

 

//call method

            var s = "Student";

            Console.WriteLine(s.AddPrefix("tbl"));

 

// خروجی

 tblStuden


 http://msdn.microsoft.com/en-us/library/bb383977.aspx

http://csharp.net-tutorials.com/csharp-3.0/extension-methods/