C# | Static Class - GeeksforGeeks (2024)

Skip to content

C# | Static Class - GeeksforGeeks (1)

Last Updated : 20 Sep, 2023

Improve

Summarize

Suggest changes

Post a comment

Like Article

Like

Save

Report

In C#, one is allowed to create a static class, by using static keyword. A static class can only contain static data members and static methods. It is not allowed to create objects of the static class and since it does not allow to create objects it means it does not allow instance constructor. Static classes are sealed, means you cannot inherit a static class from another class.

Syntax:

static class Class_Name
{
// static data members
// static method
}

In C#, the static class contains two types of static members as follows:

  • Static Data Members: As static class always contains static data members, so static data members are declared using static keyword and they are directly accessed by using the class name. The memory of static data members is allocating individually without any relation with the object.
    Syntax:
static class Class_name 
{
public static nameofdatamember;
}
  • Static Methods: As static class always contains static methods, so static methods are declared using static keyword. These methods only access static data members, they can not access non-static data members.
    Syntax:
static class Class_name {
public static nameofmethod()
{
// code
}
}

Example 1:

C#

// C# program to illustrate the

// concept of static class

using System;

namespace ExampleOfStaticClass {

// Creating static class

// Using static keyword

static class Author {

// Static data members of Author

public static string A_name = "Ankita";

public static string L_name = "CSharp";

public static int T_no = 84;

// Static method of Author

public static void details()

{

Console.WriteLine("The details of Author is:");

}

}

// Driver Class

public class GFG {

// Main Method

static public void Main()

{

// Calling static method of Author

Author.details();

// Accessing the static data members of Author

Console.WriteLine("Author name : {0} ", Author.A_name);

Console.WriteLine("Language : {0} ", Author.L_name);

Console.WriteLine("Total number of articles : {0} ",

Author.T_no);

}

}

}

Output

The details of Author is:Author name : Ankita Language : CSharp Total number of articles : 84

Example 2:

C#

// C# program to demonstrate

// the concept of static class

using System;

// declaring a static class

public static class GFG {

// declaring static Method

static void display()

{

Console.WriteLine("Static Method of class GFG");

}

}

// trying to inherit the class GFG

// it will give error as static

// class can't be inherited

class GFG2 : GFG {

public static void Main(String[] args) {

}

}

Compile Time Error:

prog.cs(20,7): error CS0709: `GFG2′: Cannot derive from static class `GFG’

Explanation: In the above example, we have a static class named as Author by using static keyword. The Author class contains static data members named A_name, L_name, and T_no, and a static method named as details(). The method of a static class is simply called by using its class name like Author.details();. As we know that static class doesn’t consist object so the data member of the Author class is accessed by its class name, like Author.A_name, Author.L_name, and Author.T_no.

Difference between static and non-static class

Static ClassNon-Static Class
Static class is defined using static keyword.Non-Static class is not defined by using static keyword.
In static class, you are not allowed to create objects.In non-static class, you are allowed to create objects using new keyword.
The data members of static class can be directly accessed by its class name.The data members of non-static class is not directly accessed by its class name.
Static class always contains static members.Non-static class may contain both static and non-static methods.
Static class does not contain an instance constructor.Non-static class contains an instance constructor.
Static class cannot inherit from another class.Non-static class can be inherited from another class.


Improve

Please Login to comment...

Similar Reads

C# | Difference between Static Constructors and Non-Static Constructors

Prerequisite: Constructors in C# Static constructors are used to initialize the static members of the class and are implicitly called before the creation of the first instance of the class. Non-static constructors are used to initialize the non-static members of the class. Below are the differences between the Static Constructors and Non-Static Con

6 min read

Static Local Function in C# 8.0

In C# 7.0, local functions are introduced. The local function allows you to declare a method inside the body of an already defined method. Or in other words, we can say that a local function is a private function of a function whose scope is limited to that function in which it is created. The type of local function is similar to the type of functi

3 min read

C# Program to Demonstrate the Static Constructor in Structure

A Structure is a well-defined data structure that can hold elements of multiple data types. It is similar to a class because both are user-defined data types and both contain a bunch of different data types. You can also use pre-defined data types. However, sometimes the user might be in need to define its own data types which are also known as Use

2 min read

Static keyword in C#

static is a modifier in C# which is applicable for the following: ClassesVariablesMethodsConstructorIt is also applicable to properties, event, and operators. To create a static member(class, variable, methods, constructor), precede its declaration with the keyword static. When a member is declared static, it can be accessed with the name of its cl

4 min read

C# Program to Inherit an Abstract Class and Interface in the Same Class

Abstract Class is the way to achieve abstraction. It is a special class that never be instantiated directly. This class should contain at least one abstract method in it and mark by abstract keyword in the class definition. The main purpose of this class is to give a blueprint for derived classes and set some rules what the derived classes must imp

3 min read

C# | How to get TypeCode for the class String

GetTypeCode() method is used to get the TypeCode of the specified string. Here TypeCode enum represents a specific type of object. In TypeCode every data type is represented by a specific number like String is represented by 18, Int32 is represented by 9, etc. Syntax: public TypeCode GetTypeCode (); Return value: This method return an enumerated co

2 min read

C# | Class and Object

Class and Object are the basic concepts of Object-Oriented Programming which revolve around the real-life entities. A class is a user-defined blueprint or prototype from which objects are created. Basically, a class combines the fields and methods(member function which defines actions) into a single unit. In C#, classes support polymorphism, inheri

5 min read

C# | Sealed Class

Sealed classes are used to restrict the users from inheriting the class. A class can be sealed by using the sealed keyword. The keyword tells the compiler that the class is sealed, and therefore, cannot be extended. No class can be derived from a sealed class. The following is the syntax of a sealed class : sealed class class_name { // data members

4 min read

C# | Math Class Fields with Examples

In C#, the Math class provides the constants and the static methods for logarithmic, trigonometric, and other mathematical functions. Math class has two fields as follows: Math.E FieldMath.PI FieldMath.E Field This field represents the natural logarithmic base, specified by the constant, e. Syntax: public const double E Program 1: To illustrate the

3 min read

C# | Math Class

In C#, Math class comes under the System namespace. It is used to provide static methods and constants for logarithmic, trigonometric, and other useful mathematical functions. It is a static class and inherits the object class. public static class Math Fields A field is a variable that is declared in a class or struct. These are considered as the m

4 min read

Article Tags :

C# | Static Class - GeeksforGeeks (3)

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

C# | Static Class - GeeksforGeeks (4)

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, check: true }), success:function(result) { jQuery.ajax({ url: writeApiUrl + 'suggestions/auth/' + `${post_id}/`, type: "GET", dataType: 'json', xhrFields: { withCredentials: true }, success: function (result) { $('.spinner-loading-overlay:eq(0)').remove(); var commentArray = result; if(commentArray === null || commentArray.length === 0) { // when no reason is availaible then user will redirected directly make the improvment. // call to api create-improvement-post $('body').append('

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); return; } var improvement_reason_html = ""; for(var comment of commentArray) { // loop creating improvement reason list markup var comment_id = comment['id']; var comment_text = comment['suggestion']; improvement_reason_html += `

${comment_text}

`; } $('.improvement-reasons_wrapper').html(improvement_reason_html); $('.improvement-bottom-btn').html("Create Improvement"); $('.improve-modal--improvement').hide(); $('.improvement-reason-modal').show(); }, error: function(e){ $('.spinner-loading-overlay:eq(0)').remove(); // stop loader when ajax failed; }, }); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ $('.improvement-reason-modal').hide(); } $('.improve-modal--improvement').show(); }); function loadScript(src, callback) { var script = document.createElement('script'); script.src = src; script.onload = callback; document.head.appendChild(script); } function suggestionCall() { var suggest_val = $.trim($("#suggestion-section-textarea").val()); var array_String= suggest_val.split(" ") var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(suggest_val.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `

${suggest_val}

`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-section-textarea').val(""); jQuery('.suggest-bottom-btn').css("display","none"); // Update the modal content const modalSection = document.querySelector('.suggestion-modal-section'); modalSection.innerHTML = `

Thank You!

Your suggestions are valuable to us.

You can now also contribute to the GeeksforGeeks community by creating improvement and help your fellow geeks.

`; }, error:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 5 Words and Maximum Character limit is 2000."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('#suggestion-section-textarea').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('

'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // load the captcha script and set the token loadScript('https://www.google.com/recaptcha/api.js?render=6LdMFNUZAAAAAIuRtzg0piOT-qXCbDF-iQiUi9KY', function() { setGoogleRecaptcha(); }); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('

'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.improvement-reason-modal').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); });

C# | Static Class - GeeksforGeeks (2024)

FAQs

What is the use of static class in C#? ›

A static class can be used as a convenient container for sets of methods that just operate on input parameters and don't have to get or set any internal instance fields. For example, in the . NET Class Library, the static System.

What is static and non-static in C#? ›

In static class, you are not allowed to create objects. In non-static class, you are allowed to create objects using new keyword. The data members of static class can be directly accessed by its class name. The data members of non-static class is not directly accessed by its class name.

How to call a static method in C#? ›

You invoke a static method by referencing the name of the type to which the method belongs; static methods don't operate on instance data. Attempting to call a static method through an object instance generates a compiler error. Calling a method is like accessing a field.

What is the difference between static and sealed classes in C#? ›

Static classes are loaded automatically by the . NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded. A sealed class cannot be used as a base class. Sealed classes are primarily used to prevent derivation.

What is the difference between static class and normal class in C#? ›

A static class is one that cannot be instantiated. Therefore, it cannot be used as a 'template" for multiple instances of some object that conforms to the class definition as a normal class can.

Can a static class inherit another class in C#? ›

Any class which does not contain instance contructor, cannot be inherited. Static class by default do not have non-static contructor (instance contructor) and that is why you cannot inherit it. Not possible to inherit static class in c#.

Can a static class have a constructor in C#? ›

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.

Can we override static methods in C#? ›

(1) Static methods cannot be overridden, they can however be hidden using the 'new' keyword. Mostly overriding methods means you reference a base type and want to call a derived method. Since static's are part of the type and aren't subject to vtable lookups that doesn't make sense.

Can a static class be instantiated in C#? ›

A static class is a high-level concept in C# programming language that doesn't need an instance for referring to its members. Plus, you cannot instantiate them.

Can we override sealed class in C#? ›

No - in order to override a method, you have to derive from it, which you can't do when the class is sealed. Basically, you need to revisit your design to avoid this requirement... You can't inherit from a sealed class, so no inheritance, no override.

Why are sealed classes faster in C#? ›

Sealed classes prevent derivation. Because they can never be used as a base class, some run-time optimizations can make calling sealed class members slightly faster.

How many types of classes are there in C#? ›

There are four types of classes in C#.

Why would you use a static class? ›

Static classes and members are usually used for data or functions that do not change in response to object state, or for utility functions that do not rely on object state at all. One common use of static classes is to hold application-level data, such as configuration settings.

Why we use static in main in C#? ›

The Main() method is the entry point a C# program from where the execution starts. Main() method must be static because it is a class level method. To invoked without any instance of the class it must be static. Non-static Main() method will give a compile-time error.

What does using static do C#? ›

C# using static directive helps us to access static members (methods and fields) of the class without using the class name.

What is the purpose of static in C? ›

A static variable possesses the property of preserving its actual value even after it is out of its scope. Thus, the static variables are able to preserve their previous value according to their previous scope, and one doesn't need to initialize them again in the case of a new scope.

Top Articles
2024 Quartz Countertop Guide: Trends, Colors, and Style Tips
Norway Demographics | Current Maine Census Data
Exclusive: Baby Alien Fan Bus Leaked - Get the Inside Scoop! - Nick Lachey
#ridwork guides | fountainpenguin
Horoscopes and Astrology by Yasmin Boland - Yahoo Lifestyle
Cumberland Maryland Craigslist
Melfme
craigslist: south coast jobs, apartments, for sale, services, community, and events
Giovanna Ewbank Nua
Hartland Liquidation Oconomowoc
Learn2Serve Tabc Answers
Silive Obituary
Morristown Daily Record Obituary
Christina Steele And Nathaniel Hadley Novel
Fsga Golf
What Is The Lineup For Nascar Race Today
Craigslistodessa
Craigslist Illinois Springfield
Jayah And Kimora Phone Number
Gina Wilson Angle Addition Postulate
F45 Training O'fallon Il Photos
Booknet.com Contract Marriage 2
Kabob-House-Spokane Photos
Jackie Knust Wendel
JVID Rina sauce set1
Turns As A Jetliner Crossword Clue
Taylored Services Hardeeville Sc
Things to do in Pearl City: Honolulu, HI Travel Guide by 10Best
Franklin Villafuerte Osorio
Aid Office On 59Th Ashland
Joplin Pets Craigslist
Skroch Funeral Home
How to Watch the X Trilogy Starring Mia Goth in Chronological Order
Jennifer Reimold Ex Husband Scott Porter
Laurin Funeral Home | Buried In Work
Quake Awakening Fragments
The Vélodrome d'Hiver (Vél d'Hiv) Roundup
Shih Tzu dogs for sale in Ireland
Cbs Fantasy Mlb
The Conners Season 5 Wiki
Kenner And Stevens Funeral Home
Foxxequeen
10 Types of Funeral Services, Ceremonies, and Events » US Urns Online
Killer Intelligence Center Download
bot .com Project by super soph
Bf273-11K-Cl
Espn Top 300 Non Ppr
Wrentham Outlets Hours Sunday
Costco Gas Price Fort Lauderdale
Philasd Zimbra
Craigslist Centre Alabama
Latest Posts
Article information

Author: Merrill Bechtelar CPA

Last Updated:

Views: 6490

Rating: 5 / 5 (50 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Merrill Bechtelar CPA

Birthday: 1996-05-19

Address: Apt. 114 873 White Lodge, Libbyfurt, CA 93006

Phone: +5983010455207

Job: Legacy Representative

Hobby: Blacksmithing, Urban exploration, Sudoku, Slacklining, Creative writing, Community, Letterboxing

Introduction: My name is Merrill Bechtelar CPA, I am a clean, agreeable, glorious, magnificent, witty, enchanting, comfortable person who loves writing and wants to share my knowledge and understanding with you.