10 Important tips for C # programmers (GO)

Source: Internet
Author: User

This article describes the 10 tips that I think are most important to C # programmers, each with a corresponding code that is easy to master for beginners.

1: Writing tests for non-public methods

Have you ever tried to write tests for a non-public method of a component? Many developers have not written, because these methods are not visible to the test project. C # allows AssemblyInfo.cs InternalsVisibleToAttribute internal members to be visible to other components by adding the following markup () in.

//Make the internals visible to the test assembly[assembly: InternalsVisibleTo("MyTestAssembly")]
2: Using the tuples type

I've seen someone create a POCO class just because the function is returning multiple values, but the types in. Net 4.0 Tuples are more appropriate, for example:

public Tuple<int, string, string> GetEmployee() {    int employeeId = 1001; string firstName = "Rudy"; string lastName = "Koertson"; //Create a tuple and return return Tuple.Create(employeeId, firstName, lastName);}
3: Substituting yield for temporary collection

When you select a part of a member from a collection, you typically create a temporary collection/list to hold the member and return it, such as the following code:

public List<int> GetValuesGreaterThan100(List<int> masterCollection) { List<int> tempResult = new List<int>(); foreach (var value in masterCollection) { if (value > 100) { tempResult.Add(value); } } return tempResult;}

To avoid such a temporary collection, you can use the yield keyword, as in the following example:

public IEnumerable<int> GetValuesGreaterThan100(List<int> masterCollection) { foreach (var value in masterCollection) { if (value > 100) { yield return value; } }}

Of course, it is also the use of LINQ to solve the above problem.

4: Tell someone you will replace a method

When you have a component, and you plan to replace one of these methods, you can first add an obsolete tag to the method to inform the client, the sample code is as follows:

[Obsolete("This method will be deprecated soon. You could use XYZ alternatively.")]public void MyComponentLegacyMethod() { //Here is the implementation}

Using this method the client will issue a warning at compile time, and if you no longer allow the client to use outdated methods, you can add an extra Boolean parameter to the stale tag, in the following example, the client but the program will fail to compile:

[Obsolete("This method is deprecated. You could use XYZ alternatively.", true)]public void MyComponentLegacyMethod() { //Here is the implementation}
5: Keep in mind that LINQ queries are deferred execution

When you write a LINQ query in. NET, LINQ queries are executed only when you access the results of a LINQ query, a feature of LINQ called Deferred execution, but it is worth noting that LINQ queries are executed once for each access result.

To avoid repeating the recurrence of a LINQ query, you can first convert the query to a list, as follows:

public void MyComponentLegacyMethod(List<int> masterCollection) { // 在下面示例中, 如果没有调用 ToList , LINQ 查询将会被执行两次 var result = masterCollection.Where(i => i > 100).ToList(); Console.WriteLine(result.Count()); Console.WriteLine(result.Average());}
6: Convert business entity types using the explicit keyword

Using explicit keywords to define conversions between business entity types, the conversion method executes automatically when a type conversion request occurs in the code, and the following is the sample code:

Classprogram {StaticvoidMain(String[] (args) {var entity =New Externalentity {Id =1001, FirstName ="Dave", LastName ="Johnson"};var convertedentity = (myentity) entity; }}Classmyentity {Publicint Id {GetSet }PublicString FullName {GetSet }PublicStaticExplicitoperator myentity(externalentity externalentity) { return new myentity {Id = Externalentity.id, full Name = externalentity.firstname + "" + Externalentity.lastname};}} class externalentity { public int Id { get; set;} public string FirstName { get; set;} public string LastName { get; set;}}                   
7: Original stack trace to keep exception

In C # code, if you throw an exception from a method in a code block like the following code, the catch ConnectDatabase exception stack is displayed only to the RunDataOperation method, so that the exception's original stack trace information is lost and the exact source of the error cannot be found.

public void RunDataOperation() { try { Intialize(); ConnectDatabase(); Execute(); } catch (Exception exception) { throw exception; }}

The code to keep the original stack trace is as follows:

public void RunDataOperation() { try { Intialize(); ConnectDatabase(); Execute(); } catch (Exception) { throw; }}
8: Use the flags tag to handle enumerations as bit fields

Adding tags to enum types in C # Flags allows enumerations to be processed as bit fields (that is, a set of flags) so that the enumeration values can be freely combined, as shown in the following example code:

class Program {    static void Main(string[] args) { int snakes = 14; Console.WriteLine((Reptile)snakes); }}[Flags]enum Reptile { BlackMamba = 2, CottonMouth = 4, Wiper = 8, Crocodile = 16, Aligator = 32}

The output of the above code is "Blackmamba, Cottonmouth, Wiper", and if there is no flags tag, the above output is 14.

9: Adding a type constraint to a generic type

When you create a generic type, you need to specify that the supplied generic type must implement the specified parameter or inherit from a specific base class:

class MyGenricClass<T> where T : IMyInterface { //Body of the class come in here}

Of course, you can do this at the method level as well:

class MyGenricClass {    public void MyGenericMethod<T>(T t) where T : IMyInterface { //Generic implementation goes in here }}
10:ienumerable type does not ensure read-only

In the type you create, a read-only property of type is exposed, IEnumerable but the caller can still modify the contents of the property through type conversion, such as:

Classprogram {StaticvoidMain(String[] args) {MyClass MyClass =New MyClass (); ((list<string>) myclass.readonlynamecollection). ADD ("##### #From client#####"); Myclass.print (); }}ClassMyClass {list<String> _namecollection =New list<String> ();public myclass () {_ Namecollection.add ( "Rob"), _namecollection.add ( "John"); _ Namecollection.add (public ienumerable<string> ReadOnlyNameCollection { Span class= "Hljs-keyword" >get {return _namecollection.asenumerable ();}} public void Print< Span class= "Hljs-params" > () {foreach (var item in readonlynamecollection) {Console.WriteLine (item);}}        

The above code modifies the list and adds a new item to avoid this situation and should be used AsReadOnly instead of AsEnumerable :

public IEnumerable<string> ReadOnlyNameCollection {    get { return _nameCollection.AsReadOnly(); }}

I hope these tips are useful for you!

Original address: Top ten Tips for C # Programmers

10 Important tips for C # programmers (GO)

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.