Microsoft Visual C# .Net Language Reference

Overview

Here’s official ...

See more details below
Available through our Marketplace sellers.
Other sellers (Paperback)
  • All (21) from $1.99   
  • New (5) from $3.07   
  • Used (16) from $1.99   
Close
Sort by
Page 1 of 1
Showing All
Note: Marketplace items are not eligible for any BN.com coupons and promotions
$3.16
Seller since 2009

Feedback rating:

(2745)

Condition:

New — never opened or used in original packaging.

Like New — packaging may have been opened. A "Like New" item is suitable to give as a gift.

Very Good — may have minor signs of wear on packaging but item works perfectly and has no damage.

Good — item is in good condition but packaging may have signs of shelf wear/aging or torn packaging. All specific defects should be noted in the Comments section associated with each item.

Acceptable — item is in working order but may show signs of wear such as scratches or torn packaging. All specific defects should be noted in the Comments section associated with each item.

Used — An item that has been opened and may show signs of wear. All specific defects should be noted in the Comments section associated with each item.

Refurbished — A used item that has been renewed or updated and verified to be in proper working condition. Not necessarily completed by the original manufacturer.

New
2002-03-12 Paperback 1 New 0735615543 Ships Within 24 Hours. Tracking Number available for all USA orders. Excellent Customer Service. Upto 15 Days 100% Money Back Gurantee. Try ... Our Fast! ! ! ! Shipping With Tracking Number. Read more Show Less

Ships from: Bensalem, PA

Usually ships in 1-2 business days

  • Canadian
  • International
  • Standard, 48 States
  • Standard (AK, HI)
  • Express, 48 States
  • Express (AK, HI)
$3.07
Seller since 2010

Feedback rating:

(1081)

Condition: New

Ships from: Monroe Township, NJ

Usually ships in 1-2 business days

  • Canadian
  • International
  • Standard, 48 States
  • Standard (AK, HI)
  • Express, 48 States
  • Express (AK, HI)
$32.68
Seller since 2010

Feedback rating:

(57)

Condition: New
"New Original US Edition, We Ship to PO BOX Address also. EXPEDITED shipping option available for certian weight packets only."

Ships from: STERLING HEIGHTS, MI

Usually ships in 1-2 business days

  • Canadian
  • International
  • Standard, 48 States
  • Standard (AK, HI)
$34.54
Seller since 2015

Feedback rating:

(1)

Condition: New
"New, Excellent customer service. Satisfaction guaranteed!! "

Ships from: Irving, TX

Usually ships in 1-2 business days

  • Canadian
  • International
  • Standard, 48 States
  • Standard (AK, HI)
$58.77
Seller since 2008

Feedback rating:

(213)

Condition: New

Ships from: Chicago, IL

Usually ships in 1-2 business days

  • Standard, 48 States
  • Standard (AK, HI)
Page 1 of 1
Showing All
Close
Sort by
Sending request ...

Overview

Here’s official documentation for the Microsoft® Visual C#® .NET language, including descriptions of all major features. This LANGUAGE REFERENCE is taken from Microsoft’s electronic product documentation for Visual C# .NET. In its printed form, this material is portable, easy to use, and easy to browse—a comprehensive alternative to the substantial online help system in Visual C# .NET Standard software.

Get the technical details you need to work with:

  • Types
  • Modifiers
  • Statements
  • Method parameters
  • Namespaces
  • Operator keywords
  • Conversion keywords
  • Access keywords
  • Literal keywords
  • XML documentation
  • Attributes
  • Preprocessor directives
Read More Show Less

Product Details

  • ISBN-13: 9780735615540
  • Publisher: Microsoft Press
  • Publication date: 2/4/2002
  • Series: Developer Reference Series
  • Pages: 404
  • Product dimensions: 7.32 (w) x 9.32 (h) x 0.86 (d)

Meet the Author

Founded in 1975, Microsoft® is the worldwide leader in software, services, and solutions that help people and businesses realize their full potential. Since 1988, Microsoft has been building accessibility options right into its products to enable everyone to personalize their PCs to make them easier and more comfortable to see, hear, and use.

Read More Show Less

Read an Excerpt

C# Keywords
  • The Keywords
  • Access Keywords
    • base
    • this
  • Conversion Keywords
    • explicit
    • implicit
    • operator
  • Literal Keywords
    • null
    • true
    • false
  • Method Parameter Keywords
    • params
    • ref
    • out
  • Modifiers
    • Access Modifiers

Part 2   C# Keywords

Read More Show Less

Table of Contents

Chapter 1: Introduction to C#

Chapter 2: C# Keywords

Chapter 3: C# Features

C# Compiler Options

Cordless Drill

Read More Show Less

First Chapter

C# Keywords
  • The Keywords
  • Access Keywords
    • base
    • this
  • Conversion Keywords
    • explicit
    • implicit
    • operator
  • Literal Keywords
    • null
    • true
    • false
  • Method Parameter Keywords
    • params
    • ref
    • out
  • Modifiers
    • Access Modifiers

Part 2   C# Keywords

The Keywords

Keywords are predefined reserved identifiers that have special meanings to the compiler. They cannot be used as identifiers in your program unless they include @ as a prefix. For example, @if is a legal identifier but if is not because it is a keyword.

The following lists each keyword used in C# and the section within this part of the book that discusses that keyword.

abstract Access Modifiers
as Operator Keywords
base Access Keywords
bool Type Keywords
break Statement Keywords
byte Type Keywords
case Statement Keywords
catch Statement Keywords
char Type Keywords
checked Statement Keywords
class Reference Types
const Access Modifiers
continue Statement Keywords
decimal Type Keywords
default Statement Keywords
delegate Reference Types
do Statement Keywords
double Type Keywords
else Statement Keywords
enum Type Keywords
event Access Modifiers
explicit Conversion Keywords
extern Access Modifiers
false Literal Keywords;
Operator Keywords
finally Statement Keywords
fixed Statement Keywords
float Type Keywords
for Statement Keywords
foreach Statement Keywords
goto Statement Keywords
if Statement Keywords
implicit Conversion Keywords
in Statement Keywords
int Type Keywords
interface Reference Types
internal Modifiers
is Operator Keywords
lock Statement Keywords
long Type Keywords
namespace Namespace Keywords
new Operator Keywords
null Literal Keywords
object Reference Types
operator Conversion Keywords
out Method Parameter
override Access Modifiers
params Method Parameter
private Modifiers
protected Modifiers
public Modifiers
readonly Access Modifiers
ref Method Parameter
return Statement Keywords
sbyte Type Keywords
sealed Access Modifiers
short Type Keywords
sizeof Operator Keywords
stackalloc Operator Keywords
static Access Modifiers
string Reference Types
struct Type Keywords
switch Statement Keywords
this Access Keywords
throw Statement Keywords
true Literal Keywords;
Operator Keywords
try Statement Keywords
typeof Operator Keywords
uint Type Keywords
ulong Type Keywords
unchecked Statement Keywords
unsafe Access Modifiers
ushort Type Keywords
using Namespace Keywords
virtual Access Modifiers
void Reference Types
volatile Access Modifiers
while Statement Keywords

Access Keywords

This section introduces the following access keywords:

  • base   Access the members of the base class.
  • this   Refer to the current object for which a method is called.

base

The base keyword is used to access members of the base class from within a derived class:

  • Call a method on the base class that has been overridden by another method.
  • Specify which base-class constructor should be called when creating instances of the derived class.

A base class access is permitted only in a constructor, an instance method, or an instance property accessor.

It is an error to use the base keyword from within a static method.

Example

In this example, both the base class, Person, and the derived class, Employee, have a method named Getinfo. By using the base keyword, it is possible to call the Getinfo method on the base class, from within the derived class.

// keywords_base.cs
// Accessing base class members
using System;
public class Person
{
protected string ssn = "444-55-6666";
protected string name = "John L. Malgraine";
      public virtual void GetInfo()
{
Console.WriteLine("Name: {0}", name);
Console.WriteLine("SSN: {0}", ssn);
}
}
class Employee: Person
{
public string id = "ABC567EFG";
      public override void GetInfo()
{
// Calling the base class GetInfo method:
base.GetInfo();
Console.WriteLine("Employee ID: {0}", id);
}
}
class TestClass {
public static void Main()
{
Employee E = new Employee();
E.GetInfo();
}
}

Output

Name: John L. Malgraine
SSN: 444-55-6666
Employee ID: ABC567EFG

For additional examples, see the sections "new" on page 65, "virtual" on page 51, and "override" on page 44.

Example

This example shows how you can specify the base-class constructor called when creating instances of a derived class.

// keywords_base2.cs
using System;
public class MyBase
{
int num;
public MyBase() {
Console.WriteLine("in MyBase()");
}
public MyBase(int i )
{
num = i;
Console.WriteLine("in MyBase(int i)");
}
   public int GetNum()
{
return num;
}
}
public class MyDerived : MyBase
{
static int i = 32;
   // This constructor will call MyBase.MyBase()
public MyDerived(int ii) : base()
{
}
   // This constructor will call MyBase.MyBase(int i)
public MyDerived() : base(i)
{
}
   public static void Main()
{
MyDerived md = new MyDerived();
MyDerived md1 = new MyDerived(1);
}
}

Output

in MyBase(int i)
in MyBase()

this

The this keyword refers to the current instance for which a method is called. Static member functions do not have a this pointer. The this keyword can be used to access members from within constructors, instance methods, and instance accessors.

The following are common uses of this:

  • To qualify members hidden by similar names, for example:
  • public Employee(string name, string alias)
    {
    this.name = name;
    this.alias = alias;
    }
  • To pass an object as a parameter to other methods, for example:
  • CalcTax(this);
    
  • To declare indexers, for example:
  • public int this [int param]
    {
    get
    {
    return array[param];
    }
    set
    {
    array[param] = value;
    }
    }

It is an error to refer to this in a static method, static property accessor, or variable initializer of a field declaration.

Example

In this example, this is used to qualify the Employee class members, name and alias, which are hidden by similar names. It is also used to pass an object to the method CalcTax, which belongs to another class.

// keywords_this.cs
// this example
using System;
public class Employee
{
public string name;
public string alias;
public decimal salary = 3000.00m;
   // Constructor:
public Employee(string name, string alias)
{
// Use this to qualify the fields, name and alias:
this.name = name;
this.alias = alias;
}
   // Printing method:
public void printEmployee()
{
Console.WriteLine("Name: {0}\nAlias: {1}", name, alias);
// Passing the object to the CalcTax method by using this:
Console.WriteLine("Taxes: {0:C}", Tax.CalcTax(this));
}
}
public class Tax
{
public static decimal CalcTax(Employee E)
{
return (0.08m*(E.salary));
}
}
public class MainClass
{
public static void Main()
{
// Create objects:
Employee E1 = new Employee ("John M. Trainer", "jtrainer");
      // Display results:
E1.printEmployee();
}
}

Output

Name: John M. Trainer
Alias: jtrainer
Taxes: $240.00

For additional examples, see the sections "class" on page 149 and "struct" on page 138.

Conversion Keywords

This section describes keywords used in type conversions:

  • explicit
  • implicit
  • operator

A conversion enables an expression of one type to be treated as another type. Conversions can be implicit or explicit, and this determines whether an explicit cast is required. For instance, in the conversion from type int to type long is implicit, so expressions of type int can implicitly be treated as type long. The opposite conversion, from type long to type int, is explicit and so an explicit cast is required.

int a = 123;
long b = a; // implicit conversion from int to long
int c = (int) b; // explicit conversion from long to int

Some conversions are defined by the language. Programs may also define their own conversions.

explicit

The explicit keyword is used to declare an explicit user-defined type conversion operator. For example:

class MyType
{
public static explicit operator MyType(int i)
{
// code to convert from int to MyType
}
}

Unlike implicit conversion, explicit conversion operators must be invoked via a cast.

int i;
MyType x = (MyType)i; // int-to-MyType requires cast

Omitting the cast results in a compile-time error.

If a conversion operation can cause exceptions or lose information, you should mark it explicit. This prevents the compiler from silently invoking the conversion operation with possibly unforeseen consequences.

Example

The following example defines a struct, Digit, that represents a single decimal digit. An operator is defined for conversions from byte to Digit, but because not all bytes can be converted to a Digit, the conversion is explicit.

// cs_keyword_explicit.cs
using System;
struct Digit
{
byte value;
public Digit(byte value)
{
if (value<0 || value>9) throw new ArgumentException();
this.value = value;
}
   // define explicit byte-to-Digit conversion operator:
public static explicit operator Digit(byte b)
{
Console.WriteLine("conversion occurred");
return new Digit(b);
}
}
class Test
{
public static void Main()
{
byte b = 3;
Digit d = (Digit)b; // explicit conversion
}
}

Output

conversion occurred

implicit

The implicit keyword is used to declare an implicit user-defined type conversion operator. For example:

class MyType
{
public static implicit operator int(MyType m)
{
// code to convert from MyType to int
}
}

Implicit conversion operators can be called implicitly, without being specified by explicit casts in the source code.

MyType x;
int i = x; // implicitly call MyType's MyType-to-int conversion operator

By eliminating unnecessary casts, implicit conversions can improve source code readability. However, because implicit conversions can occur without the programmer's specifying them, care must be taken to prevent unpleasant surprises. In general, implicit conversion operators should never throw exceptions and never lose information so that they can be used safely without the programmer's awareness. If a conversion operator cannot meet those criteria, it should be marked explicit.

Example

The following example defines a struct, Digit, that represents a single decimal digit. An operator is defined for conversions from Digit to byte, and because any Digit can be converted to a byte, the conversion is implicit.

// cs_keyword_implicit.cs
using System;
struct Digit
{
byte value;
   public Digit(byte value)
{
if (value < 0 || value > 9) throw new ArgumentException();
this.value = value;
}
// define implicit Digit-to-byte conversion operator:
public static implicit operator byte(Digit d)
{
Console.WriteLine( "conversion occurred" );
return d.value;
}
}
class Test
{
public static void Main()
{
Digit d = new Digit(3);

// implicit (no cast) conversion from Digit to byte
byte b = d;
}
}

Output

conversion occurred

operator

The operator keyword is used to declare an operator in a class or struct declaration. An operator declaration can take one of the following four forms:


public static 
result-type 
operator 
unary-operator 
( 
op-type operand 
)
public static result-type operator binary-operator (
op-type operand ,
op-type2 operand2
)
public static implicit operator conv-type-out ( conv-type-in operand )
public static explicit operator conv-type-out ( conv-type-in operand )

where:

result-type

The type of the operator's result.

unary-operator

One of: +   -   !   ~   ++   --   true   false

op-type

The type of the first (or only) parameter.

operand

The name of the first (or only) parameter.

binary-operator

One of: +   -   *   /   %   &   |   ^   <<   >>   ==   !=   >   <   >=   <=

op-type2

The type of the second parameter.

operand2

The name of the second parameter.

conv-type-out

The target type of a type conversion operator.

conv-type-in

The type of the input to a type conversion operator.

Remarks

The first two forms declare user-defined operators that overload built-in operators. Note that not all the built-in operators can be overloaded (see "Overloadable Operators" on page 170). At least one of op-type and op-type2 must be the enclosing type (that is, the type of which the operator is a member). This prevents redefining the integer addition operator, for instance.

The last two forms declare conversion operators. Exactly one of conv–type–in and conv–type–out must be the enclosing type (that is, a conversion operator can only convert from its enclosing type to some other type, or from some other type to its enclosing type).

Operators can only take value parameters, not ref or out parameters.

Any operator declaration can be preceded by an optional attribute list.

Example

The following is an extremely simplified class for rational numbers. It overloads the + and * operators to perform fractional addition and multiplication, and also provides an operator that converts fractions to doubles.

// cs_keyword_operator.cs
using System;
class Fraction
{
int num, den;
public Fraction(int num, int den)
{
this.num = num;
this.den = den;
}
   // overload operator +
public static Fraction operator +(Fraction a, Fraction b)
{
return new Fraction(a.num * b.den + b.num * a.den,
a.den * b.den);
}
// overload operator *
public static Fraction operator *(Fraction a, Fraction b)
{
return new Fraction(a.num * b.num, a.den * b.den);
}
   // define operator double
public static implicit operator double(Fraction f)
{
return (double)f.num / f.den;
}
}
class Test
{
public static void Main()
{
Fraction a = new Fraction(1, 2);
Fraction b = new Fraction(3, 7);
Fraction c = new Fraction(2, 3);
Console.WriteLine((double)(a * b + c));
}
}

Output

0.880952380952381

Literal Keywords

C# has the following literal keywords:

  • null
  • true
  • false

null

The null keyword is a literal that represents a null reference, one that does not refer to any object. null is the default value of reference-type variables.

See Also

Default Values Table (pg. 164)

true

In C#, the true keyword can be used as an overloaded operator or as a literal:

  • true Operator
  • true Literal

true Operator

User-defined types can define a true operator that returns the bool value true to indicate true and returns false otherwise. This is useful for types that represent true, false, and null (neither true nor false), as used in databases.

Such types can be used for the controlling expression in if, do, while, and for statements and in conditional expressions.

If a type defines operator true, it must also define operator false.

A type cannot directly overload the conditional logical operators (&& and ||), but an equivalent effect can be achieved by overloading the regular logical operators and operators true and false.

true Literal

The true keyword is a literal of type bool representing the boolean value true.

Example

// cs_keyword_true.cs
using System;
class test
{
public static void Main()
{
bool a = true;
Console.WriteLine( a ? "yes" : "no" );
}
}

Output

Yes

See Also

Operators (pg. 169),  (pg. 16, 74) false

In C#, the false keyword can be used as an overloaded operator or as a literal:

  • false Operator
  • false Literal

false Operator

User-defined types can define a false operator that returns the bool value true to indicate false and returns false otherwise. This is useful for types that represent true, false, and null (neither true nor false), as used in databases.

Such types can be used for the controlling expression in if, do, while, and for statements and in conditional expressions.

If a type defines operator false, it must also define operator true.

A type cannot directly overload the conditional logical operators (&& and ||), but an equivalent effect can be achieved by overloading the regular logical operators and operators true and false.

false Literal

The false keyword is a literal of type bool representing the boolean value false.

Example

// cs_keyword_false.cs
using System;
class test
{
public static void Main()
{
bool a = false;
Console.WriteLine( a ? "yes" : "no" );
}
}

Output

No

See Also

Operators (pg. 169), true (pg. 15, 73)

Method Parameter Keywords

If a parameter is declared for a method without ref or out, the parameter can have a value associated with it. That value can be changed in the method, but the changed value will not be retained when control passes back to the calling procedure. By using a method parameter keyword, you can change this behavior.

This section describes the keywords you can use when declaring method parameters:

  • params
  • ref
  • out

params

The params keyword lets you specify a method parameter that takes an argument where the number of arguments is variable.

No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.

Example

// cs_params.cs
using System;
public class MyClass
{

public static void UseParams(params int[] list)
{
for ( int i = 0 ; i < list.Length ; i++ )
Console.WriteLine(list[i]);
Console.WriteLine();
}

public static void UseParams2(params object[] list)
{
for ( int i = 0 ; i < list.Length ; i++ )
Console.WriteLine((object)list[i]);
Console.WriteLine();
}
public static void Main()
{
UseParams(1, 2, 3);
UseParams2(1, 'a', "test");

int[] myarray = new int[3] {10,11,12};
UseParams(myarray);
}
}

Output

1
2
3
1
a
test
10
11
12

ref

The ref method parameter keyword on a method parameter causes a method to refer to the same variable that was passed into the method. Any changes made to the parameter in the method will be reflected in that variable when control passes back to the calling method.

To use a ref parameter, the argument must explicitly be passed to the method as a ref argument. The value of a ref argument will be passed to the ref parameter.

An argument passed to a ref parameter must first be initialized. Compare this to an out parameter, whose argument does not have to be explicitly initialized before being passed to an out parameter.

An overload will occur if declarations of two methods differ only in their use of ref.

A property is not a variable and cannot be passed as a ref parameter.

For information on passing an array, see "Passing Arrays Using ref and out" on page 254.

Example

// cs_ref.cs
using System;
public class MyClass
{
public static void TestRef(ref char i)
{
// The value of i will be changed in the calling method
i = 'b';
}
   public static void TestNoRef(char i)
{
// The value of i will be unchanged in the calling method
i = 'c';
}
   // This method passes a variable as a ref parameter; the value of the
// variable is changed after control passes back to this method.
// The same variable is passed as a value parameter; the value of the
// variable is unchanged after control is passed back to this method.
public static void Main()
{
      char i = 'a';    // variable must be initialized
TestRef(ref i); // the arg must be passed as ref
Console.WriteLine(i);
TestNoRef(i);
Console.WriteLine(i);
}
}

Output

b
b

out

The out method parameter keyword on a method parameter causes a method to refer to the same variable that was passed into the method. Any changes made to the parameter in the method will be reflected in that variable when control passes back to the calling method.

Declaring an out method is useful when you want a method to return multiple values. A method that uses an out parameter can still return a value. A method can have more than one out parameter.

To use an out parameter, the argument must explicitly be passed to the method as an out argument. The value of an out argument will not be passed to the out parameter.

A variable passed as an out argument need not be initialized. However, the out parameter must be assigned a value before the method returns.

An overload will occur if declarations of two methods differ only in their use of out.

A property is not a variable and cannot be passed as an out parameter.

For information on passing an array, see "Passing Arrays Using ref and out" on page 254.

Example

// cs_out.cs
using System;
public class MyClass
{
public static int TestOut(out char i)
{
i = 'b';
return -1;
}
   public static void Main()
{
char i; // variable need not be initialized
Console.WriteLine(TestOut(out i));
Console.WriteLine(i);
}
}

Output

-1
b

Modifiers

Modifiers are used to modify declarations of types and type members. This section introduces the C# modifiers:

Modifier Purpose
Access Modifiers
  • public
  • private
  • internal
  • protected
Specify the declared accessibility of types and type members.
abstract Indicate that a class is intended only to be a base class of other classes.
const Specify that the value of the field or the local variable cannot be modified.
event Declare an event.
extern Indicate that the method is implemented externally.
override Provide a new implementation of a virtual member inherited from a base class.
readonly Declare a field that can only be assigned values as part of the declaration or in a constructor in the same class.
sealed Specify that a class cannot be inherited.
static Declare a member that belongs to the type itself rather than to a specific object.
unsafe Declare an unsafe context.
virtual Declare a method or an accessor whose implementation can be changed by an overriding member in a derived class.
volatile Indicate that a field can be modified in the program by something such as the operating system, the hardware, or a concurrently executing thread.

Access Modifiers

Access modifiers are keywords used to specify the declared accessibility of a member or a type. This section introduces the four access modifiers:

  • public
  • protected
  • internal
  • private

The following five accessibility levels can be specified using the access modifiers:

public   protected   internal   internal protected   private

This section also introduces the following topics:

  • Accessibility Levels
  • Accessibility Domain
  • Restrictions on Using Accessibility Levels

Accessibility Levels

When access is allowed to a member, it said to be accessible. Otherwise, it is inaccessible. Use the access modifiers, public, protected, internal, or private, to specify one of the following declared accessibilities for members.

Declared accessibility Meaning
public Access is not restricted.
protected Access is limited to the containing class or types derived from the containing class.
internal Access is limited to the current project.
protected internal Access is limited to the current project or types derived from the containing class.
private Access is limited to the containing type.

Only one access modifier is allowed for a member or type, except for the protected internal combination.

Access modifiers are not allowed on namespaces. Namespaces have no access restrictions.

Depending on the context in which a member declaration takes place, only certain declared accessibilities are permitted. If no access modifier is specified in a member declaration, a default accessibility is used.

Top-level types, which are not nested into other types, can only have internal or public accessibility. The default accessibility for these types is internal.

Nested types, which are members of other types, can have declared accessibilities as indicated in the following table.

Members of Default member accessibility Allowed declared accessibility of the member
enum public None
class private public

protected

internal

private

protected internal

interface public None
struct private public

internal

private

The accessibility of a nested type depends on its accessibility domain, which is determined by both the declared accessibility of the member and the accessibility domain of the immediately containing type. However, the accessibility domain of a nested type cannot exceed that of the containing type.

See Also

Accessibility Domain (pg. 23), Restrictions on Using Accessibility Levels (pg. 24)

Accessibility Domain

The accessibility domain of a member specifies where, in the program sections, a member can be referenced. If the member is nested within another type, its accessibility domain is determined by both the accessibility level of the member and the accessibility domain of the immediately containing type.

The accessibility domain of a top-level type is at least the program text of the project in which it is declared. That is, the entire source files of this project. The accessibility domain of a nested type is at least the program text of the type in which it is declared. That is, the type body, including any nested types. The accessibility domain of a nested type never exceeds that of the containing type. These concepts are demonstrated in the following example.

Example

This example contains a top-level type, T1, and two nested classes, M1 and M2. The classes contain fields with different declared accessibilities. In the Main method, a comment follows each statement to indicate the accessibility domain of each member. Notice that the statements that attempt to reference the inaccessible members are commented out. If you want to see the compiler errors caused by referencing an inaccessible member, remove the comments one at a time.

// cs_Accessibility_Domain.cs
using System;
namespace MyNameSpace
{
public class T1
{
public static int myPublicInt;
internal static int myInternalInt;
private static int myPrivateInt = 0;

public class M1
{
public static int myPublicInt;
internal static int myInternalInt;
private static int myPrivateInt = 0;
}
private class M2
{
public static int myPublicInt = 0;
internal static int myInternalInt = 0;
private static int myPrivateInt = 0;
}
}

public class MainClass
{
public static int Main()
{
// Access to T1 fields:
T1.myPublicInt = 1; // Access is unlimited
T1.myInternalInt = 2; // Accessible only in current project
// T1.myPrivateInt = 3; // Error: inaccessible outside T1

// Access to the M1 fields:
T1.M1.myPublicInt = 1; // Access is unlimited
T1.M1.myInternalInt = 2; // Accessible only in current project
// T1.M1.myPrivateInt = 3; // Error: inaccessible outside M1

// Access to the M2 fields:
// T1.M2.myPublicInt = 1; // Error: inaccessible outside T1
// T1.M2.myInternalInt = 2; // Error: inaccessible outside T1
// T1.M2.myPrivateInt = 3; // Error: inaccessible outside M2

return 0;
}
}
}

See Also

Accessibility Levels (pg. 22), Restrictions on Using Accessibility Levels (pg. 24)

Restrictions on Using Accessibility Levels

When you declare a type, it is essential to see if that type has to be at least as accessible as another member or type. For example, the direct base class must be at least as accessible as the derived class. The following declarations will result in a compiler error, because the base class BaseClass is less accessible than MyClass:

class BaseClass {...}
public class MyClass: BaseClass {...} // Error

The following table summarizes the restrictions on using declared accessibility levels.

Context Remarks
Classes The direct base class of a class type must be at least as accessible as the class type itself.
Interfaces The explicit base interfaces of an interface type must be at least as accessible as the interface type itself.
Delegates The return type and parameter types of a delegate type must be at least as accessible as the delegate type itself.
Constants The type of a constant must be at least as accessible as the constant itself.
Fields The type of a field must be at least as accessible as the field itself.
Methods The return type and parameter types of a method must be at least as accessible as the method itself.
Properties The type of a property must be at least as accessible as the property itself.
Events The type of an event must be at least as accessible as the event itself.
Indexers The type and parameter types of an indexer must be at least as accessible as the indexer itself.
Operators The return type and parameter types of an operator must be at least as accessible as the operator itself.
Constructors The parameter types of a constructor must be at least as accessible as the constructor itself.

Example

The following example contains erroneous declarations of different types. The comment following each declaration indicates the expected compiler error.

// Restrictions_on_Using_Accessibility_Levels.cs
// CS0052 expected as well as CS0053, CS0056, and CS0057
// To make the program work, change access level of both class B
// and MyPrivateMethod() to public.
using System;
// A delegate:
delegate int MyDelegate();
class B
{
// A private method:
static int MyPrivateMethod()
{
return 0;
}
}
public class A
{
// Fields:
public B myField = new B(); // Error: The type B is less accessible
// than the field A.myField.
// Constants:
public readonly B myConst = new B(); // Error: The type B is less accessible
// than the constant A.myConst.
   // Methods:
public B MyMethod()
{
return new B(); // Error: The type B is less accessible
} // than the method A.MyMethod.
   // Properties:
public B MyProp
{
set
{
}
} // Error: The type B is less accessible than the property A.MyProp
   // Delegates:
MyDelegate d = new MyDelegate(B.MyPrivateMethod);
// Even when B is declared public, you still get the error:
// "The parameter B.MyPrivateMethod is not accessible due to
// protection level."
   // Operators:
public static B operator + (A m1, B m2)
{
return new B(); // Error: The type B is less accessible
// than the operator A.operator +(A,B)
}
static void Main()
{
Console.Write("Compiled successfully");
}
}

See Also

Accessibility Domain (pg. 23), Accessibility Levels (pg. 22)

Read More Show Less

Customer Reviews

Be the first to write a review
( 0 )
Rating Distribution

5 Star

(0)

4 Star

(0)

3 Star

(0)

2 Star

(0)

1 Star

(0)

Your Rating:

Your Name: Create a Pen Name or

Barnes & Noble.com Review Rules

Our reader reviews allow you to share your comments on titles you liked, or didn't, with others. By submitting an online review, you are representing to Barnes & Noble.com that all information contained in your review is original and accurate in all respects, and that the submission of such content by you and the posting of such content by Barnes & Noble.com does not and will not violate the rights of any third party. Please follow the rules below to help ensure that your review can be posted.

Reviews by Our Customers Under the Age of 13

We highly value and respect everyone's opinion concerning the titles we offer. However, we cannot allow persons under the age of 13 to have accounts at BN.com or to post customer reviews. Please see our Terms of Use for more details.

What to exclude from your review:

Please do not write about reviews, commentary, or information posted on the product page. If you see any errors in the information on the product page, please send us an email.

Reviews should not contain any of the following:

  • - HTML tags, profanity, obscenities, vulgarities, or comments that defame anyone
  • - Time-sensitive information such as tour dates, signings, lectures, etc.
  • - Single-word reviews. Other people will read your review to discover why you liked or didn't like the title. Be descriptive.
  • - Comments focusing on the author or that may ruin the ending for others
  • - Phone numbers, addresses, URLs
  • - Pricing and availability information or alternative ordering information
  • - Advertisements or commercial solicitation

Reminder:

  • - By submitting a review, you grant to Barnes & Noble.com and its sublicensees the royalty-free, perpetual, irrevocable right and license to use the review in accordance with the Barnes & Noble.com Terms of Use.
  • - Barnes & Noble.com reserves the right not to post any review -- particularly those that do not follow the terms and conditions of these Rules. Barnes & Noble.com also reserves the right to remove any review at any time without notice.
  • - See Terms of Use for other conditions and disclaimers.
Search for Products You'd Like to Recommend

Recommend other products that relate to your review. Just search for them below and share!

Create a Pen Name

Your Pen Name is your unique identity on BN.com. It will appear on the reviews you write and other website activities. Your Pen Name cannot be edited, changed or deleted once submitted.

 
Your Pen Name can be any combination of alphanumeric characters (plus - and _), and must be at least two characters long.

Continue Anonymously

    If you find inappropriate content, please report it to Barnes & Noble
    Why is this product inappropriate?
    Comments (optional)