Answers for "c# difference between static and nonstatic"

C#
1

c# difference between static and nonstatic

// (SCROLL DOWN TO SEE CODE EXAMPLES) ---->
/* Description:
A static class cannot be instantiated, we cannot use the new keyword 
to create a variable of the class type. 

C# fields must be declared inside a class. However, if we declare a method
or a field as static, we can call the method or access the field using the
name of the class (No instance is required).

We can also use the static keyword when defining a field. With this feature, 
we can create a single field that is shared among all objects created from a 
single class. Non-static fields are local to each instance of an object.

When you define a static method or field, it does not have access to any 
instance fields defined for the class; it can use only fields that are marked 
as static. Furthermore, it can directly invoke only other methods in the 
class that are marked as static; nonstatic (instance) methods or fields first
require creation of an object on which to call them. */

// Non-Static Exmaple:
using System;
using System.Collections.Generic;
using System.Text;
namespace TestiClass
{
    class Program
    {
        public int calculation(int x, int y)
        {
            int val = x * y;
            return val;
        } 
        static void Main(string[] args)
        {
            Program x = new Program();
            int newval = x.calculation(12,12);
            Console.WriteLine(newval);
            Console.ReadKey();
        }
    }
} 

// Static Example:
using System;
using System.Collections.Generic;
using System.Text;
namespace TestiClass
{
    class Program
    {
        public static int calculation(int x, int y)
        {
            int val = x * y;
            return val;
        } 
        static void Main(string[] args)
        {
            Console.WriteLine(calculation(12,12));
            Console.ReadKey();
        }
    }
}
Posted by: Guest on August-15-2021

Code answers related to "c# difference between static and nonstatic"

C# Answers by Framework

Browse Popular Code Answers by Language