Skip to content
- Tutorials
- Python Tutorial
- Taking Input in Python
- Python Operators
- Python Data Types
- Python Loops and Control Flow
- Python Functions
- Python OOPS Concept
- Python Data Structures
- Python Exception Handling
- Python File Handling
- Python Exercises
- Java
- Java Programming Language
- Java Collections
- Java 8 Tutorial
- Java Programs
- Java Interview Questions
- Java Exercises
- Java Quiz
- Java Projects
- Advance Java
- Programming Languages
- System Design
- Interview Corner
- Computer Science Subjects
- DevOps
- Linux
- Software Testing
- Databases
- Android
- Excel
- Mathematics
- Python Tutorial
- DSA
- Data Structures
- Algorithms
- Analysis of Algorithms
- Searching Algorithms
- Sorting Algorithms
- Greedy Algorithms
- Dynamic Programming
- Graph Algorithms
- Pattern Searching
- Recursion
- Backtracking
- Divide and Conquer
- Mathematical Algorithms
- Geometric Algorithms
- Bitwise Algorithms
- Randomized Algorithms
- Branch and Bound
- Algorithms Tutorial
- DSA Tutorial
- Practice
- All DSA Problems
- Problem of the Day
- Company Wise Coding Practice
- GfG SDE Sheet
- Practice Problems Difficulty Wise
- Language Wise Coding Practice
- Curated DSA Lists
- Competitive Programming
- Company Wise SDE Sheets
- DSA Cheat Sheets
- Top Interview Questions
- Puzzles
- Data Science
- Web Tech
- Courses
-
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 Class Non-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 :
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
'); $('.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(); } }, }); });