📜 ⬆️ ⬇️

"Hidden" utility C #

I offer my free translation of the question from stackoverflow, which seemed useful to me and sits in the favorites. Something I took from MSDN (mostly clippings from the Russian edition), something from blogs.
All of us, C # developers, know the basic C # commands. I mean declarations, conditions, cycles, operators, etc.
Some of us even know about Generics , anonymous types , lambdas , linq , ...

But, what are the really secretive features and tricks of C # that even fans and experts don't always know about?

Keywords


yield by Michael Stum Used in an iterator block to provide the value of an enumerator object or to report an end of iteration
yield return <expression>; yield break ;

var by Michael Stum . Declares a variable
var index;

using() statement by kokos. Provides convenient syntax to ensure proper use of IDisposable objects.
using (System.IO.StreamReader sr = new System.IO.StreamReader(@"C:\Users\Public\Documents\test.txt"))
{
string s = null;
while((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}

readonly by kokos . The readonly keyword is a modifier that can be used for fields. If the field declaration contains the readonly modifier, the assignment of values ​​to such fields can only occur as part of the declaration or in a constructor in the same class.
class Age
{
readonly int _year;
Age(int year)
{
_year = year;
}
void ChangeYear()
{
//_year = 1967; // Compile error if uncommented.
}
}

as by Mike Stone

as / is by Ed Swangren
')
as / is (improved) by Rocketpants

default by deathofrats

global:: by pzycoman . When the context-sensitive global keyword precedes the operator , it refers to the global namespace, which is the default namespace for any C # program and is not otherwise named.
class TestClass : global::TestApp { }

volatile by Jakub Ĺ turc . The volatile keyword indicates that a field can be edited by several threads running simultaneously. Fields declared as volatile are not optimized by the compiler, which provides access through a separate stream. This ensures that the field has the most current value at any time.
class VolatileTest
{
public volatile int i;


public void Test (int _i)
{
i = _i;
}
}

extern alias by Jakub Ĺ turc . In some cases, it may be necessary to provide references to two versions of assemblies with the same complete type names. For example, you need to use two or more versions of an assembly in the same application. Using an external assembly alias, you can include namespaces for each assembly in a wrapper within the root-level namespaces named for this alias, which allows them to be used in a single file.
/r:GridV1=grid.dll
/r:GridV2=grid20.dll
Here are the external aliases GridV1 and GridV2. To use these aliases in a program, create a link to them using the extern keyword. Example.
extern alias GridV1;
extern alias GridV2;
GridV1 :: Grid is the Grid control from grid.dll, and GridV2 :: Grid is the Grid control from grid20.dll.

Attributes


DefaultValue by Michael Stum. Attribute to set the default value of the parameter.

ObsoleteAttribute by DannySmurf. Marks program elements that are no longer used.

DebuggerDisplayAttribute by Stu . Determines how a class or field is displayed in the debugger variable windows.

DebuggerBrowsable . Specifies the presence and method of displaying members in the debugger variable windows.

DebuggerStepThrough by bdukes . Specifies the DebuggerStepThroughAttribute class. This class cannot be inherited.

ThreadStaticAttribute by marxidad. Indicates that the value of a static field is unique for each thread.

FlagsAttribute by Martin Clarke. Indicates that an enumeration can be processed as a bitfield, which is a set of flags.
[SerializableAttribute]
[AttributeUsageAttribute(AttributeTargets.Enum, Inherited = false)]
[ComVisibleAttribute(true)]
public class FlagsAttribute : Attribute

ConditionalAttribute by AndrewBurns

Syntax


?? operator by kokos. Operator ?? is called an operator that supports the value NULL, and is used to determine the default value for zero value types, as well as for reference types. It returns the left operand if it is not NULL, otherwise it returns the right operand.
class NullCoalesce
{
static int? GetNullableInt()
{
return null;
}


static string GetStringValue ()
{
return null;
}

static void Main ()
{
// ?? operator example.
int? x = null;

// y = x, unless x is null, in which case y = -1.
int y = x ?? -one;

// Assign i to return value of method, unless
// return value is null, in which case assign
// default value of int to i.

int i = GetNullableInt () ?? default (int);

string s = GetStringValue ();
// ?? also works with reference types.
// Display contents of s, unless s is null,
// in which case display "Unspecified".

Console.WriteLine (s ?? "Unspecified");
}
}

number flaggings by Nick Berardi
Decimal = M
Float = F
Double = D


// for example
double d = 30D;

one-parameter lambdas by Keith
x => x.ToString() //simplify so many calls

auto properties by Keith
Public int MyId { get; private set; }

namespace aliases by Keith
using web = System.Web.UI.WebControls;
using win = System.Windows.Forms;


web :: Control aWebControl = new web :: Control ();
win :: Control aFormControl = new win :: Control ();

verbatim string literals with @ by Patrick
"c:\\program files\\oldway"
@"c:\program file\newway"

(@ symbol helps to exclude special characters)

enum values ​​by lfoust .Enum need not be int.
public enum MyEnum : long
{
Val1 = 1,
Val2 = 2
}

Any numeric value can be enum:
MyEnum e = (MyEnum)123;

event operators by marxidad. Use the event keyword to announce an event in the publisher class.
public class SampleEventArgs
{
public SampleEventArgs(string s) { Text = s; }
public String Text {get; private set;} // readonly
}
public class Publisher
{
// Declare the delegate (if using non-generic pattern).
public delegate void SampleEventHandler(object sender, SampleEventArgs e);


// Declare the event.
public event SampleEventHandler SampleEvent;

// Wrap the event in a protected virtual method
// to enable the event.
protected virtual void RaiseSampleEvent ()
{
// Raise the event by using the () operator.
SampleEvent (this, new SampleEventArgs ("Hello"));
}
}

format string brackets by Portman

property accessor accessibility modifiers by xanadont

ternary operator ( :? ) by JasonS . condition? first_expression: second_expression;

checked and unchecked operator by Binoj Antony

Language Features


Nullable types by Brad Barker. A type that allows null values ​​are instances of the System.Nullable (T) structure. A type that admits NULL values ​​can represent the correct range of values ​​for its base value type and an optional null value. For example, for a nullable called “Int32 type, allowing for NULL values”, you can assign any value from -2,147,483,648 to 2,147,483,647 or null.
Use operator ?? , to assign a default value applied when a type that allows NULL values, with a current value of null, is assigned to a type that does not allow values ​​of NULL, for example, int? x = null; int y = x ?? -one;

Currying by Brian Leahy

anonymous types by Keith. Anonymous types offer a convenient way to encapsulate a set of read-only properties into a single object without the need for an explicit type definition. The type name is created by the compiler and is not available at the source code level. The type of properties is displayed by the compiler. The following example shows an anonymous type that is initialized with two properties: Amount and Message.
var v = new { Amount = 108, Message = "Hello" };

__makeref __reftype __refvalue by Judah Himango

object initializers by lomaxx. One of the novelties of C # 3.0 ... Allows you to do such changes:
Person p = new Person() {FirstName="John",LastName="Doe",Phone="602-123-1234",City="Phoenix"};

That is, define properties without using a constructor.

Extension Methods by marxidad . Extension methods allow you to “add” methods to existing types without creating a new derived type, recompiling or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods in the extended type. For client code written in C # and Visual Basic, there is no visible difference between invoking an extension method and invoking methods that are actually defined in a type.
class ExtensionMethods2
{


static void Main ()
{
int [] ints = {10, 45, 15, 39, 21, 26};
var result = ints. OrderBy (g => g);
foreach (var i in result)
{
System.Console.Write (i + "");
}
}
}
// Output: 10 15 21 26 39 45

Partial methods by Jon Erickson. It is possible to divide the definition of a class or structure , interface or method between two or more source files. Each source file contains a definition of a type or method, and all parts are combined when the application is compiled.
public partial class Employee
{
public void DoWork()
{
}
}


public partial class Employee
{
public void GoToLunch ()
{
}
}

C # by John Asbeck preprocessor directives

DEBUG pre-processor directive by Robert Durgin #if debug-code defined in such a block will be executed only during debag. It is convenient to make more detailed conclusions of exceptions when developing.

Operator overloads by SefBkn .

boolean operators by Rob Gough

Visual studio features


snippets by DannySmurf . Visual Studio's development environment includes a feature called “code snippets”. Code snippets are ready-made snippets of code that can be quickly inserted into your code. For example, the for code fragment creates an empty for loop. Some code fragments are surrounding, i.e. allow you to first select the lines of code, and then the code fragment in which the selected lines will be included. For example, if you select the necessary lines of code and then activate a fragment of the for code, a block of the for loop will be created, within which the selected lines of code will be. Code snippets speed up writing programs and make the process more reliable.
Imkho can try templates from Resharper .

Framework


TransactionScope by KiwiBastard. Makes the code block transactional. This class cannot be inherited.

Mutex by Mutex

System.IO.Path by ageektrapped. Performs operations on instances of the String class that contain the path information of a file or directory. These operations are performed in a cross-platform way.

WeakReference by Juan Manuel . WeakReference weak link that points to an object, but allows you to delete it to the garbage collector.

Methods and Properties


String.IsNullOrEmpty() method by KiwiBastard. Indicates whether the specified String object is null (Nothing in Visual Basic) or the string is Empty .

List.ForEach() method by KiwiBastard
using System;
using System.Collections.Generic;


class program
{
static void Main ()
{
List <String> names = new List <String> ();
names.Add ("Bruce");
names.Add ("Alfred");
names.Add ("Tim");
names.Add ("Richard");

// Display the contents of the List out using the "Print" delegate.
names.ForEach (Print);

// The following demonstrates the Anonymous Delegate feature of C #
// to display the contents of the list.
names.ForEach (delegate (String name)
{
Console.WriteLine (name);
});
}

private static void Print (string s)
{
Console.WriteLine (s);
}
}
/ * This code will produce output to the following:
* Bruce
* Alfred
* Tim
* Richard
* Bruce
* Alfred
* Tim
* Richard
* /

BeginInvoke() , EndInvoke() methods by Will Dean

Nullable<T>.HasValue and Nullable<T>. Value Nullable<T>. Value properties by Rismo

GetValueOrDefault method by John Sheehan. Returns the value of the current Nullable (T) object or the specified default value.

Tips & Tricks


uppercase comparisons by John. Based on the book “CLR via C #”, Microsoft optimized the code for making UPPERCASE comparisons. (and NOT LOWERCASE, for example)

LINQBridge by Duncan Smart

Parallel Extensions by Joel Coehoorn . The report covers the main components of Parallel FX Jun 2008 CTP and gives examples of Parallel FX application.

original ©
PS So much smoker over the formatting of the code, but Habr doesn’t want to listen to something = (he said it in his blog , everything is displayed almost right there.

Progg it

Source: https://habr.com/ru/post/56279/


All Articles