C# Class Fields and Properties

C# Class Fields and Properties

Fields

  • Fields represent read-only or readable/writable data values.
  • Fields can be static, which are considered part of the type state.
  • Fields can also be instance (non-static), which are considered part of the object state.
  • It is strongly recommended to declare fields as private to prevent the type or object’s state from being corrupted by external code.

Properties

Properties allow setting or querying the logical state of a type or object using simple, field-style syntax, while ensuring the state is not corrupted. Properties that act on types are called static properties, and those that act on objects are called instance properties. Properties can have no parameters or multiple parameters (rare, but common in collection classes).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
	using System;
	
	public sealed class SomeType
	{                            //  1  
	// Nested class  
	   private class SomeNestedType { }                //  2  
	
	   // Constant, read­only, and static read/write field   
	   private const Int32 c_SomeConstant = 1;            //  3     
	
	   private readonly String m_SomeReadOnlyField = "2";     //  4    
	
	   private static Int32 s_SomeReadWriteField = 3;      //  5  
	
	   // Type constructor  
	   static SomeType() { }                                  //  6  
	
	   // Instance constructors  
	   public SomeType(Int32 x) { }                           //  7  
	
	   public SomeType() { }                                  //  8 
	
	   // Instance and static methods  
	   private String InstanceMethod() { return null; }       // 9   
	
	   public static void Main() { }                        // 10 
	
	   // Instance property  
	   public Int32 SomeProp
	   {                                // 11      
	       get { return 0; }                                // 12      
	       set { }                                          // 13  
	   }
	
	   // Instance parameterful property (indexer) 
	   public Int32 this[String s]
	   {                          // 14       
	       get { return 0; }                                // 15        
	       set { }                                          // 16  
	   }
	
	   // Instance event  
	   public event EventHandler SomeEvent;                  // 17  
	}

enter image description here

enter image description here

Built with Hugo
Theme Stack designed by Jimmy