"C # Advanced Series" 08 stories about parameters

Source: Internet
Author: User

Optional parameters and named parameters

Not much to say, on the code, naturally understand

classProgram {Static voidMain (string[] args) {            varTroy =NewTroy (); Troy. HelloWorld (1);//at this point both B and C are 0Troy. HelloWorld (1,2);//at this point B is 2,c is 0, the above two is the optional parameter playTroy. HelloWorld (A:1B:2);//named parameter GameplayTroy. HelloWorld (b:2A:1);//even if the order is disrupted, the effect is the same        }    }     Public classTroy { Public voidHelloWorld (intAintb =0,intC=default(int)) {//here the B and C parameters are optional parameters//Note the default (int) play, which represents the value of int. //This is the first time I've known about this usage, but it's a great way to play because it can reduce the number of magic in your code.            You may think that 0 is not a magic number, but I think it is necessary to make the code a little bit easier to understand. //even if you do not use magic numbers, then default (DateTime) to determine whether the datetime value is the default value, is it better than the new DateTime ()?         }    }

The default parameter actually applies attributes OptionalAttribute and Defaultparametervalueattribute to this parameter after the C # compiler compiles. is not supported by the CLR, but is unique to C #.

These two things all look so good, but the good things are not necessarily really nice.

It is recommended to use command parameters, but do not change order in order to swap. In fact, for a powerful tool like VS, named parameters are only useful when there are very many parameters.

If you have too many parameters, you should consider reducing the number of parameters. You can consider extracting a parameter object, passing the value of the parameter when the object is good.

Although I like to use the default parameters, in fact it is very useful, especially for overloading, you sometimes do not need to write two functions.

But this is actually a pit point.

If you like to use it as much as I do, people in your team also like to use it. At the end of the time, you'll find that this thing always fills the inside of the function with all sorts of branches, and your argument list gets longer. O (︶^︶) o ay

If you don't understand, then you can look at one of my Code maintenance stories, imagine that you're maintaining a large system with complex business, and then the rhythm will often happen.

       //at first, Troy wrote a function of greeting.         Public voidHello () {Console.WriteLine ("Hello"); //here are a series of handshakes, smiles and other actions        }        //later, the boss said internationalization, but also to be able to greet in English. You have selected the default parameters and, to ensure that the previous code runs smoothly, the default is False         Public voidGreetBOOLIsenglish=false)        {            if(Isenglish) {Console.WriteLine ("Hello"); }            Else{Console.WriteLine ("Hello"); }            //here are a series of handshakes, smiles and other actions        }        //The above step is OK, but after two days, the boss and Daniel said some foreigners may not shake hands, he chose to hug. So Daniel changed the code:         Public voidGreetBOOLIsenglish =false,BOOLWhether to choose hug =false)        {            if(Isenglish) {Console.WriteLine ("Hello"); }            Else{Console.WriteLine ("Hello"); }            if(choose whether to hug) {Console.WriteLine ("Hug"); }            Else{Console.WriteLine ("Handshake"); }            //Here's a series of smiles and things like that.}

Of course, even now, the above code seems to be just branching out, but please put yourself in your mind if the business of this system is complex, if there is a need, if not just a Console.WriteLine so simple operation.

When the fourth time to change, the new members of the project team have no choice of dishes. First he is not familiar with the business, dare not to change, he may even be familiar with too lazy to change, because changed it is already very troublesome (do not trust your teammates, I am such a lazy person (☆_☆)), then this time he can only silently choose to add a default parameter.

There is a fourth, will definitely have fifth, every time want to refactor feel more and more difficult, the heart more and more empty, had to go with the default parameters, after everyone together, this code has almost 10 branches, we are afraid to change.

If you do not choose to add default parameters from the beginning, but instead write an overloaded function to extract the public parts, then do you think there will be such a problem?

However, there is no bird, even if I know so clearly, I often feel that I am adding the third time the default parameter completely without any problems, stealing a little lazy to get off work, the code can still see, and when I come back to change the next time, I found that the default parameters have become 5. O (︶^︶) o ay

The story of Out and ref

The CLR does not differentiate between out and ref, and the resulting IL code is identical, except that the metadata is distinguished by a bit value.

Out means that the reference type is passed, but it does not need to be called when the parameter is initialized and the out parameter must be written when the function is finished.

This parameter is initialized when ref calls and does not require that the ref parameter be written when the function is finished.

Actually, in C, this thing is a pointer, and we're here to pass the value of the address.

If there is a large value type of the parameter, such as a large struct.

The use of this method only passes an address value, instead of pressing the value inside each struct into the stack.

In addition, because ref is better than the out-of-the-out,out, you can definitely pass the value of this parameter and read the code more easily.

Pramas passing a variable number of arguments

This online a lot of, I use the most is String.Format method, can refer to this to understand.

However, note that this will have a performance penalty, because the Pramas one-dimensional array passed, is actually allocated in the heap space, initialization ah, garbage collection Ah, will have an impact.

Design specifications for parameters and return types

When declaring a method's parameter type, the type should be declared according to the lowest interface type, the stronger interface type, the base class, and the derived class from high to low precedence.

Because using an interface or base class will make your approach more flexible, you can choose a larger choice.

The return type is the opposite, preventing it from being limited to a particular type.

The above is the author said, there is a reason, but the specific circumstances of the specific analysis, we should all go to declare object, that all OK?

The author's meaning is obviously not so. I think you can choose the most suitable strong type parameter at the first time, but the next time there is a similar function, and two parameters have a common interface or base class, then can you consider the type of parameter to weaken it? This obviously makes the code more flexible.

But do not use a direct object such as, do not over-design, and always use the most satisfied with the needs of the one, do not consider the future completely, because you simply predict the future.

"C # Advanced Series" 08 stories about parameters

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.