×

C# Tutorial

Basics of .Net

C# Basics

C# Fundamentals

C# Operators

C# Loops

C# Type Conversions

C# Exception Handling

C# String Class

C# Arrays

C# List

C# Stack

C# Queue

C# Collections

C# Character Class

C# Class and Object

C# Namespaces

C# Delegates

C# Constructors

C# Inheritance

C# Operator Overloading

C# Structures

C# File Handling

C# Convert.ToInt32()

C# Int32 (int) Struct

C# DateTime Class

C# Uri Class

C# Database Connectivity

C# Windows

C# Other Topics

C# Q & A

C# Programs

C# Find O/P

C# - Create Class and Object

Learn, how to create a class with some of the data members and member functions, then create an object to access them?
[Last updated : March 21, 2023]

As we know that, C# is an object oriented programming language. Class and Object are the important part of the Object Oriented programming approach.

In this program, we are going to implement a program using class and object in C#, here we will also use constructor to initialize data members of the class.

Syntax of Class Creation

class <class_name>
{
    //private data members
    //constructors
    //public member functions
}

Syntax of Object Creation

<class_name> <object_name> = new <contructor>;

Example

Sample s = new Sample ();

Note: First alphabet of class name should be capital conventionally.

C# Class and Object Creation Example

// C# program to create class and object
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1 {
  // Class definition
  class Sample {
    private int X;
    private int Y;

    public Sample() {
      X = 5;
      Y = 10;
    }

    public void read() {
      Console.Write("Enter value of X: ");
      X = Convert.ToInt32(Console.ReadLine());

      Console.Write("Enter value of Y: ");
      Y = Convert.ToInt32(Console.ReadLine());
    }

    public void print() {
      Console.WriteLine("Value of X: " + X);
      Console.WriteLine("Value of Y: " + Y);
    }
  }
  
  class Program {
    static void Main(string[] args) {
      // Creating object of the class
      Sample S1 = new Sample();

      S1.print();

      Sample S2 = new Sample();

      S2.read();
      S2.print();

    }
  }
}

Output

Value of X: 5
Value of Y: 10
Enter value of X: 12
Enter value of Y: 15
Value of X: 12
Value of Y: 15

Explanation

In this program, there is a class named "Sample", it contains default constructor and two private data members and two public methods that are operated on data members.

C# Basic Programs »

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.