Static classes and static class members in C# explained (2024)

Static classes and static class members in C# explained (1)

byJoydip Kanjilal

Contributor

how-to

Jan 28, 20194 mins

C#Microsoft .NETProgramming Languages

Declare static classes and static members of a class to improve performance of your .NET applications.

Static classes and static class members in C# explained (2)

Credit: diane39/Getty Images

The static keyword in the C# programming language allows you to define static classes and static members.

A static class is similar to a class that is both abstract and sealed. The difference between a static class and a non-static class is that a static class cannot be instantiated or inherited and that all of the members of the class are static in nature.To declare a class as static, you should mark it with the static keyword in the class declaration.

There is no behavior in a static class or member, so there isn’t any point in allowing a static class to be inherited either. A static class can only have static members — you cannot declare instance members (methods, variables, properties, etc.) in a static class. You can have a static constructor in a static class but you cannot have an instance constructor inside a static class.

When to use a static class in C#

When should you go for a static class? Typically you can implement helper or utility classes as static classes since they don’t need to be instantiated or inherited and generally contain a collection of some reusable methods and properties. The following code listing illustrates what a static class in C# looks like.

public static class FileLogger { public static void Log(string message) { //Method to log data in a text file } }

When to use static methods in C#

Static methods are methods that don’t need an instance of the class to be invoked— they can be called on the class itself. Note that static methods can only access static class members. You can have static methods inside a static class or a non-static class. Also, you can have a static constructor in a static class or a non-static class. A static constructor is used to initialize the static members of a class. The static constructor of a class is invoked the first time a static member of the class is accessed.

Why should we use static methods? They’re a bit faster in execution than non-static methods, i.e., instance methods. The reason is that the runtime passes the this pointer as an implicit parameter to the non-static or instance methods. Note that for a non-static method the compiler emits the callvirt instruction even if the method is non-virtual. If you make your methods static, the compiler emits non-virtual call sites, eliminating the extra check for whether the instance is null. This might give you some performance benefits.

Therefore, if the application you are building is a performance-critical one, it may be worthwhile to use static types and methods in your code. The performance gains may be appreciable if your code makes large number of calls to such types and members.

The following code snippet illustrates what a static method looks like.

public static void Log(string message) { string filePath = @"F:IDGLog.txt"; using (StreamWriter streamWriter = new StreamWriter(filePath, true)) { streamWriter.WriteLine(message); streamWriter.Close(); } }

How to use static members of a class in C#

The CLR divides system memory into three distinct regions: the stack, the heap, and the high frequency heap. Since static objects can be accessed directly without creating instances of the class, they must exist in the memory throughout the lifetime of the application; they don’t need to be garbage collected. Therefore, static objects are stored in the high frequency heap. You typically have one high frequency heap for each application domain.

Let’s now take a look at static members of a class. Again, a static object is one that persists in the memory the entire time the application is in execution. Extending the logging example above, the following code listing illustrates what a FileLogger class with static members would look like.

public static class FileLogger { private static readonly object lockObject = new object(); public static string FilePath { get; set; } public static void Log(string message) { lock (lockObject) { if(!string.IsNullOrEmpty(FilePath)) using (StreamWriter streamWriter = new StreamWriter(FilePath, true)) { streamWriter.WriteLine(message); streamWriter.Close(); } } } }

Note the usage of the static property named FilePath. To ensure thread safety, the lock keyword has been used. A check has been made inside the Log() method to verify that the value of the FilePath property is non-null and not empty.

Remember, when application speed is of the essence, it might pay to use static methods. You can use them in both static classes and non-static classes.

Related content

  • how-toException handling in Java: The basics Learn everything you need to throw, try, catch, and clean up after Java exceptions in your programs.By Jeff FriesenSep 12, 202421 minsJavaProgramming LanguagesSoftware Development
  • newsTypeScript 5.6 now generally available Update of Microsoft’s strongly typed JavaScript disallows nullish and truthy checks on syntax that never varies on nullishness or truthiness.By Paul KrillSep 11, 20243 minsJavaScriptTypescriptProgramming Languages
  • newsRust 1.81 stabilizes Error trait Stabilization of the Error trait in Rust core allows the usage of the trait in #![no_std] libraries. Sort algorithms also were improved in the latest Rust release. By Paul KrillSep 09, 20243 minsRustProgramming LanguagesSoftware Development
  • newsC language slumps in Tiobe popularity index Longtime leading programming language for systems development dropped to fourth in the Tiobe index for September, its lowest position ever. By Paul KrillSep 09, 20243 minsC LanguageProgramming LanguagesSoftware Development
  • Resources
  • Videos
Static classes and static class members in C# explained (2024)
Top Articles
How To Pay Online In India As A Foreigner - Lost With Purpose
Cleaning Ancient Coins
Hannaford Weekly Flyer Manchester Nh
Best Big Jumpshot 2K23
What Are the Best Cal State Schools? | BestColleges
Archived Obituaries
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Kraziithegreat
New Slayer Boss - The Araxyte
Kansas Craigslist Free Stuff
<i>1883</i>'s Isabel May Opens Up About the <i>Yellowstone</i> Prequel
Ub Civil Engineering Flowsheet
More Apt To Complain Crossword
Santa Clara Valley Medical Center Medical Records
World History Kazwire
How Much Is Tj Maxx Starting Pay
Costco Gas Foster City
2024 U-Haul ® Truck Rental Review
Dexter Gomovies
24 Hour Walmart Detroit Mi
Craiglist Tulsa Ok
Walgreens San Pedro And Hildebrand
Jayah And Kimora Phone Number
R Personalfinance
Maxpreps Field Hockey
Governor Brown Signs Legislation Supporting California Legislative Women's Caucus Priorities
Apartments / Housing For Rent near Lake Placid, FL - craigslist
Elite Dangerous How To Scan Nav Beacon
Kitchen Exhaust Cleaning Companies Clearwater
King Soopers Cashiers Check
Myra's Floral Princeton Wv
Gridwords Factoring 1 Answers Pdf
Restaurants Near Calvary Cemetery
Jambus - Definition, Beispiele, Merkmale, Wirkung
Nicole Wallace Mother Of Pearl Necklace
Ukg Dimensions Urmc
The Complete Guide To The Infamous "imskirby Incident"
Enjoy4Fun Uno
Craigslist Tulsa Ok Farm And Garden
Saybyebugs At Walmart
Anguilla Forum Tripadvisor
Autum Catholic Store
Fool's Paradise Showtimes Near Roxy Stadium 14
Celsius Claims Agent
Brown launches digital hub to expand community, career exploration for students, alumni
Large Pawn Shops Near Me
Ciara Rose Scalia-Hirschman
Publix Store 840
Strawberry Lake Nd Cabins For Sale
Craigslist Monterrey Ca
Palmyra Authentic Mediterranean Cuisine مطعم أبو سمرة
Latest Posts
Article information

Author: Madonna Wisozk

Last Updated:

Views: 5572

Rating: 4.8 / 5 (48 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Madonna Wisozk

Birthday: 2001-02-23

Address: 656 Gerhold Summit, Sidneyberg, FL 78179-2512

Phone: +6742282696652

Job: Customer Banking Liaison

Hobby: Flower arranging, Yo-yoing, Tai chi, Rowing, Macrame, Urban exploration, Knife making

Introduction: My name is Madonna Wisozk, I am a attractive, healthy, thoughtful, faithful, open, vivacious, zany person who loves writing and wants to share my knowledge and understanding with you.