官术网_书友最值得收藏!

Identifiers

These keywords are used in any part of the C# program and are reserved. Identifiers are special keywords and are treated differently by the compiler.

These are the identifiers that are reserved by C#:

  • abstract: This informs you that things that come with the abstract modifier are yet to complete or have a missing definition. We will discuss this in detail on day four.
  • as: This can be used in a cast operation. In other words, we can say that this checks the compatibility between two types.
The as keyword falls in the operator category of keywords; refer to https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/operator-keywords.

The following is the small code snippet that demonstrates the as identifier:

public class Stackholder 
{ 
public void GetAuthorName(Person person) 
    { 
var authorName = person as Author; 
Console.WriteLine(authorName != null ? $"Author is {authorName.Name}" :"No author."); 
    } 
 
} 
 
//Rest code is omitted 

The preceding code snippet has a method that writes the name of an author to the console window. With the help of the as operator, it is called by the following code:

private static void ExampleIsAsOperator() 
{ 
WriteLine("isas Operator"); 
var author = new Author{Name = "Gaurav Aroraa"}; 
 
WriteLine("Author name using as:\n"); 
stackholder.GetAuthorName(author); 
 
} 

This will produce the following result:

public class TeamMember :Person 
{ 
public override string Name { get; set; } 
public void GetMemberName() 
    { 
     Console.WriteLine($"Member name:{Name}"); 
    } 
} 
 
public class ContentMember :TeamMember 
{ 
public ContentMember(string name) 
    { 
     base.Name = name; 
    } 
public void GetContentMemberName() 
    { 
     base.GetMemberName(); 
    } 
} 

This is a very simple example used to showcase the power of base. Here, we are just using base class members and methods to get the expected output:

  • bool: This is an alias of structureSystem.Boolean that helps declare variables. This has two values: true or false. We will discuss this in detail in the upcoming section, Data types.
  • break: The keyword is self-explanatory; it breaks something within a particular code execution, which could be a flow statement (for loop) or the termination of a code block (switch). We will discuss this in detail in the upcoming section on loop and statements.
  • byte: This helps declare variables of an unsigned integer. This is an alias of System.Byte. We will discuss this in detail in the upcoming section.
  • case: This is used with the Switch statement, which then tends to a code block of execution based on some condition. We will discuss switch case on day three.
  • catch: This keyword is a catch block of exception handling blocks, that is, try..catch..finally. We will discuss exception handling in detail on day six.
  • char: This keyword is useful when we declare a variable to store characters that belong to structure System.Char. We will discuss this in detail in the data type section.
  • checked: Sometimes, you might face overflow values in your program. Overflow exception means that you assigned a larger value than the max value of the assignee data type. The compiler raises the overflow exception and the program terminates. The keyword checks force the compiler to make sure that overflow will not happen to the scenario when the compiler misses it. To understand this better, look at the following code snippet:
int sumWillthrowError = 2147483647 + 19; //compile time error

This will generate a compile-time error. As soon as you write the preceding statement, you get the following error:

The following code snippet is a modified code, as shown in the preceding figure. With this modification, the new code will not generate a compile-time error:

Private static void CheckOverFlowExample()
{
var maxValue = int.MaxValue;
var addSugar = 19;
var sumWillNotThrowError = maxValue + addSugar;
WriteLine($"sum value:{sumWillNotThrowError} is not the correct value because it is larger than {maxValue}.");
}

The preceding code will never throw an overflow exception, but it would not give the correct sum; it gives -2147483647 as a result of 2147483647 + 19 because the actual sum will exceed the maximum positive value of an integer, that is, 2147483647. It will produce the following output:

In real-world programs, we can't take a risk with wrong calculations. We should use the checked keyword to overcome such situations. Let's rewrite the preceding code using checked keywords:

private static void CheckOverFlowExample() 
{ 
const int maxValue = int.MaxValue; 
const int addSugar = 19; 
var sumWillNotThrowError = checked(maxValue+addSugar); //compile time error 
WriteLine( 
$"sum value:{sumWillNotThrowError} is not the correct value because it is larger than {maxValue}."); 
} 

As soon as you write the code using the checked keyword, you will see the following compile-time error:

Now let's discuss more keywords of C#:

  • class: This keyword helps us declare classes. A C# class would contain members, methods, variables, fields, and so on (we will discuss these in detail on day four). Classes are different from structures; we will discuss this in detail in the Classes versus structures section.
  • const: This keyword helps us declare constant fields or constant locals. We will discuss this in detail on day three.
  • continue: This keyword is the opponent of break. It passes control to the next iteration in the flow statements, that is, while, do, for, and foreach. We will discuss this in detail in the upcoming sections.
  • decimal: This helps us declare a data type of 128-bit. We will discuss this in detail in the Data types section.
  • default: This is the keyword that tells us the default condition in a switch statement. We can also use the default as a literal to get the default values; we will discuss this on day three.
  • delegate: This helps declare a delegate type that is similar to method signature. We will discuss this in detail on day six.
  • do: This executes a statement repeatedly until it meets the expression condition of false. We will discuss this in the upcoming section.
  • double: This helps declare simple 64-bit floating point values. We will discuss this in detail in the upcoming section.
  • else: This comes with the if statement and executes the code statement that does not fall within the if condition. We will discuss this in detail in the coming section.
  • enum: This helps create enumerations. We will discuss this on day four.
  • event: This helps declare an event in a publisher class. We will discuss this in detail on day six.
  • explicit: This is one of the conversion keywords. This keyword declares a user-defined type conversion operator. We will discuss this in detail in the upcoming section.
  • false: A bool value indicates the false condition, result, or Operator. We will discuss this in detail in the upcoming sections.
  • finally: This is a part of exception handling blocks. Finally, a block is always executed. We will discuss this in detail on day four.
  • fixed: This is used in unsafe code and is helpful in preventing GC allocation or relocation. We will discuss this in detail on day six.
  • float: This is a simple data type that stores a 32-bit floating point value. We will discuss this in detail in the upcoming section.
  • for: The for keyword is a part of flow statements. With the use of the for loop, you can run a statement repeatedly until a specific expression is reached. We will discuss this in detail in the upcoming section.
  • foreach: This is also a flow statement, but it works only on elements for collections or arrays. This can be exited using the goto, return, break, and throw keywords. We will discuss this in detail in the upcoming section.
  • goto: This redirects the control to another part with the help of a label. In C#, goto is typically used with the switch..case statement. We will discuss this in detail in the upcoming sections.
  • if: This is a conditional statement keyword. It typically comes with the if...else statement. We will discuss this in detail in the upcoming sections.
  • implicit: Similar to the explicit keyword, this helps declare an implicit user-defined conversion. We will discuss this in detail in the upcoming sections.
  • in: A keyword helps detect the collection from where we need to iterate through members in the foreach loop. We will discuss this in detail in the upcoming sections.
  • int: This is an alias of structure System.Int32 and a data type that stores signed 32-bit integer values. We will discuss this in detail in the upcoming sections.
  • interface: This keyword helps declare an interface that can only contain methods, properties, events, and indexers (we will discuss this on day four).
  • internal: This is an access modifier. We will discuss this in detail on day four.
  • is: Similar to the as operator, is is also a keyword operator.
  • This is a code example showing the is operator:
public void GetStackholdersname(Person person) 
{ 
if (person is Author) 
    { 
     Console.WriteLine($"Author name:{((Author)person).Name}"); 
    } 
elseif (person is Reviewer) 
    { 
     Console.WriteLine($"Reviewer name:{((Reviewer)person).Name}"); 
    } 
elseif(person is TeamMember) 
    { 
     Console.WriteLine($"Member name:{((TeamMember)person).Name}"); 
    } 
else 
    { 
     Console.Write("Not a valid name."); 
    } 
 
} 

For complete explanation of is and as operators, refer to https://goo.gl/4n73JC.

  • lock: This represents a critical section of the code block. With the use of the lock keyword, we will get a mutual exclusion lock of an object, and it will get released after execution of the statement. This generally comes with the use of threading. Threading is beyond the scope of this book. For more details, refer to https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/lock-statement and https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/threading/index.
  • long: This helps declare variables to store signed 64-bit integers values, and it refers to structure System.Int64. We will discuss this in detail in the upcoming sections.
  • namespace: This helps define namespaces that declare a set of related objects. We will discuss this in details on day four.
  • new: The new keyword can be an operator, a modifier, or a constraint. We will discuss this in detail on day four.
  • null: This represents a null reference. It does not refer to any object. The default value of reference type is null. This is helpful while working with nullable types.
  • object: This is an alias of System.Object, the universal type in .NET world. It accepts any data type instead of null.
  • operator: This helps overload the built-in operator. We will discuss this in detail in the upcoming sections..
  • out: This is a contextual keyword and will be discussed in detail on day four.
  • override: This keyword helps override or extend the implementation of abstract or virtual members, methods, properties , indexer, or event. We will discuss this in detail on day four.
  • params: This helps define method parameters with a variable number of arguments. We will discuss this in detail on day four.
  • private: This is an access modifier and will be discussed on day four.
  • protected: This is an access modifier and will be discussed on day four.
  • public: This is an access modifier that sets the availability through the application and will be discussed on day four.
  • readonly: This helps us declare field declaration as read-only. We will discuss this in detail on day four.
  • ref: This helps pass values by reference. We will discuss this in detail on day four.
  • return: This helps terminate the execution of a method and returns the result for the calling method. We will discuss this in detail on day four.
  • sbyte: This denotes System.SByte and stores signed 8-bit integer values. We will discuss this in detail in the upcoming sections.
  • sealed: This is a modifier that prevents further usage/extension. We will discuss this in detail on day four.
  • short: This denotes System.Int16 and stores signed 16-bit integer values. We will discuss this in detail in the upcoming sections.
  • sizeof: This helps get the size in bytes of the inbuilt type and/or unmanaged type. For unmanaged and all other types apart from inbuilt data types, the unsafe keyword is required.
  • The following code is explained sizeof using built-in types:
private static void SizeofExample() 
{ 
WriteLine("Various inbuilt types have size as mentioned below:\n"); 
WriteLine($"The size of data type int is: {sizeof(int)}"); 
WriteLine($"The size of data type long is: {sizeof(long)}"); 
WriteLine($"The size of data type double is: {sizeof(double)}"); 
WriteLine($"The size of data type bool is: {sizeof(bool)}"); 
WriteLine($"The size of data type short is: {sizeof(short)}"); 
WriteLine($"The size of data type byte is: {sizeof(byte)}"); 
} 

The preceding code produces the following output:

Let's discuss more C# keywords; these keywords are very important and play a vital role while writing real-world programs:

  • static: This helps us declare static members and will be discussed in detail on day four.
  • string: This helps store unicode characters. It is a reference type. We will be discussing this in more detail in the upcoming section, String.
  • struct: This helps us declare a struct type. Struct type is a value type. We will be discussing this in more detail in the upcoming section, Classes versus. structs.
  • switch: This helps declare a switch statement. Switch is a selection statement, and we will be discussing it on day three.
  • this: This this keyword helps us access the members of the current instance of a class. It is also a modifier and we will be discussing on day four. Note that the this keyword has a special meaning for the extension method. Extension methods are beyond the scope of this book; refer to https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods for more detail.
  • throw: This helps throw a system or custom exceptions. We will be discussing this in detail on day six.
  • true: Similar to false, we discussed this earlier. It represents a Boolean value and can be a literal or operator. We will discuss this in more detail in the upcoming section.
  • try: This represents a try block of exception handling. Try block is one of the other three blocks that helps handle any unavoidable errors or instances of programs. All three blocks are jointly called exceptional handling blocks. The try block always comes first. This block contains the code that could throw an exception. We will discuss this in more detail on day six.
  • typeof: This helps get the type object for a desired type. Also, at runtime, you can get the type of object with the help of the GetType() method.

    The following code snippet shows the typeof() method in action:
private static void TypeofExample() 
{ 
var thisIsADouble = 30.3D; 
WriteLine("using typeof()"); 
WriteLine($"System.Type Object of {nameof(Program)} is {typeof(Program)}\n"); 
var objProgram = newProgram(); 
WriteLine("using GetType()"); 
WriteLine($"Sytem.Type Object of {nameof(objProgram)} is {objProgram.GetType()}"); 
WriteLine($"Sytem.Type Object of {nameof(thisIsADouble)} is {thisIsADouble.GetType()}"); 
} 

The preceding code will generate the following result:

These are the unsigned data types, and these data types store values without sign (+/-):

  • uint: This helps declare a variable of an unsigned 32-bit integer. We will be discussing this in detail in the upcoming section.
  • ulong: This helps declare a variable of an unsigned 65-bit integer. We will be discussing this in detail in the upcoming section.
  • unchecked: This keyword works exactly opposite to checked. The code block that threw a compile-time error with the use of the checked keyword will not generate any compile-time exception with the use of the unchecked keyword.
    Let's rewrite the code that we wrote using the checked keyword and see how the unchecked keyword works exactly opposite to checked:
private static void CheckOverFlowExample() 
{ 
const int maxValue = int.MaxValue; 
const int addSugar = 19; 
//int sumWillthrowError = 2147483647 + 19; //compile time error 
var sumWillNotThrowError = unchecked(maxValue+addSugar); 
//var sumWillNotThrowError = checked(maxValue + addSugar); //compile time error 
WriteLine( 
$"sum value:{sumWillNotThrowError} is not the correct value because it is larger than {maxValue}."); 
} 

The preceding code will run smoothly but will give the wrong result, that is, -2147483647.

You can find more detail on the checked and unchecked keywords by referring to https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/checked.

  • unsafe: This helps execute an unsafe code block that generally uses pointers. We will be discussing this in detail on day six.
  • ushort: This helps declare a variable of an unsigned 16-bit integer. We will be discussing this in more detail in the upcoming section, Data types.
  • using: The using keyword works like a directive or statement. Let's consider the following code example:
using System;

The preceding directive provides everything that belongs to the System namespace:

using static System.Console;

The preceding directive helps us call static members. After inclusion of the preceding directive in the program, we can directly call static members, methods, and so on, as shown in the following code:

Console.WriteLine("This WriteLien is without using static directive");
WriteLine("This WriteLien is called after using static directive");

In the preceding code snippet, in first statement, we called Console.WriteLine, but in the second statement, there is no need to write the class name, so we can directly call the WriteLine method.

On the other hand, the using statement helps us perfectly use the IDisposable classes. The following code snippet tells us how a using statement is helpful while we are working with disposable classes (these classes use the IDisposable interface):

public class DisposableClass : IDisposable 
{ 
public string GetMessage() 
    { 
     return"This is from a Disposable class."; 
    } 
protected virtual void Dispose(bool disposing) 
    { 
     if (disposing) 
        { 
         //disposing code here 
        } 
    } 
 
public void Dispose() 
    { 
       Dispose(true); 
       GC.SuppressFinalize(this); 
    } 
} 
private static void UsingExample() 
{ 
using (var disposableClass = new DisposableClass()) 
    { 
     WriteLine($"{disposableClass.GetMessage()}"); 
    } 
} 

The preceding code produces the following output:

C# keywords virtual and void have a special meaning: one allows the other to override it, while the other is a used as a return type when the method returns nothing. Let's discuss both in detail:

  • virtual: If the virtual keyword is used, it means that it allows methods, properties, indexers, or events to override in a derived class. We will be discussing this in more detail on day four.
  • void: This is an alias of the System.Void type. When void uses the method, it means the method does not have any return type. For instance, take a look at the following code snippet:
public void GetAuthorName(Person person) 
{ 
var authorName = person as Author; 
Console.WriteLine(authorName != null ? $"Author is {authorName.Name}" :"No author."); 
} 

In the preceding code snippet, the getAuthorName() method is of void type; hence, it does not return anything.

  • while: While is a flow statement that executes the specific code block until a specified expression evaluates false. We will be discussing this in more detail in the upcoming section, Flow statements.
主站蜘蛛池模板: 伊春市| 博客| 纳雍县| 新郑市| 应用必备| 阳春市| 轮台县| 长兴县| 莱阳市| 汝城县| 聂拉木县| 西安市| 东丽区| 维西| 孟村| 新和县| 武平县| 徐汇区| 和龙市| 花垣县| 六盘水市| 新竹市| 四子王旗| 青浦区| 东平县| 江阴市| 攀枝花市| 绥中县| 黄平县| 诏安县| 敦化市| 普兰店市| 子长县| 垣曲县| 榕江县| 甘德县| 营口市| 祁东县| 渑池县| 永定县| 阳东县|