C # default keyword

Source: Internet
Author: User

As far as I know, the default keyword can be used in C #. One is used in the Switch statement, and the other is used in the generic type. The two methods are as follows: 1. In the switch statement, if no case expression matches the switch value, the control is passed to the statement following the optional default label. If no default tag exists, the control is passed outside the switch.

Code
1int id = int32.Parse (Console. ReadLine ());
2 switch (id)
3 {
4 case 1:
5 Console. WriteLine ("Lee ");
6 break;
7 case 2:
8 Console. WriteLine ("Tang ");
9 break;
10 default:
11 Console. WriteLine ("Sorry, no one match this ID! ");
12 break;
13}
14
 

2. How to assign the default value to parameterized type T when the following conditions are unknown in the generic class and generic method: whether T is a reference type or a value type, if T is of the value type, whether it is a value or a structure.


Code
1 public class GenericClass <T>
2 {
3 public T dosomething (arg)
4 {
5 T temp = default (T );
6
7 if (arg! = Null)
8 {
9 temp = arg. Favs;
10}
11 return temp;
12}
13 //
14}
 

Given a variable T of the parameterized type t, the Statement T = null is valid only when t is of the reference type; only when T is of the numerical type rather than the structure, statement t = 0 can be used normally. The solution is to use the default keyword, which returns NULL for the reference type and zero for the value type. For the structure, this keyword returns each structure member whose Initialization is zero or empty, depending on whether the structure is a value type or a reference type.

Related Article

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.