search

Objects in C#

Sep 03, 2024 pm 03:04 PM
c#c# tutorial

The following article provides an outline for Objects in C#. As already known, C# is an object-oriented programming language and is pronounced as C Sharp. Though C# has been evolved from C++, both differentiate from each other. The basic differences can be understood through C++ vs C#.

The object is an instance of a class. Here memory is allocated dynamically for providing the output of a given program. So, how can we explain this dynamic allocation? Objects are created to access different functions or variables that are defined under the class. So, an object does not know which data type it is actually going to access. So after getting the value from the accessed elements, it would arrange the memory dynamically.

Creating an Object

In general, an object can be created in 2 ways. One of them is by using the “new” command.

The general syntax for the object is below:

Class-name object-name = new Class-name();

And then, by using the object-name, we can access respective methods and variables that are defined inside the class.

Another way of defining an object is by reference to another object. Something like assigning the value.

Code:

Class-name object-name1 = new Class-name();
Class-name object-name2;
Object-name2=object-name1;

And we can access the variable and methods in the class using the objects object-name1 and object-name2.

Examples of Objects in C#

Here we are going to have one example for each way of creating an object in C#.

Below is a program for finding the square of a number.

Code:

using System;
class Square
{
public int side;
public Square(int a)
{
side=a;
}
public int Sq()
{
return side*side;
}
}
class First
{
static void Main(String [] args)
{
int result;
Square s= new Square(4);
result=s.Sq();
Console.WriteLine("Square of the given number is " + result);
}
}

Output:

Objects in C#

  • We have created a class Square and wrote two functions inside the class. One function, which is also a constructor (Function name same as for Class name), is for inputting in the value of a number and the other for doing the actual operation.
  • In our class First which has the main function inside it, we have initialized our object ‘s’ and passed in the parameter, for which number we actually want to perform the square operation.
  • And we declared a variable result; we are passing the output of the object accessed method ‘Sq’, which does the actual operation.
  • Finally, outputting the square result in our console.

For our next way of creating an object, an example is as below:

Code:

using System;
class Square
{
public int side;
public Square(int a)
{
side=a;
}
public int Sq()
{
return side*side;
}
}
class First
{
static void Main(String [] args)
{
int result1,result2;
Square s1= new Square(4);
Square s2;
s2=s1;
result1=s1.Sq();
result2=s2.Sq();
Console.WriteLine("Square of the given number is " + result1);
Console.WriteLine("Square of the given number is " + result2);
}
}

Output:

Objects in C#

And to an extension to this, we can even assign value to our variable using an object. Let’s see how we can do that.

Code:

using System;
class Square
{
public int Side;
public Square(int side)
{
Side=side;
}
public int Sq()
{
return Side*Side;
}
}
class First
{
static void Main(String [] args)
{
int result1,result2,result3;
Square s1= new Square(4);
Square s2= new Square(6);
result1=s1.Sq();
result2=s2.Sq();
s2.Side=7;
result3=s2.Sq();
Console.WriteLine("Square of the given number is " + result1);
Console.WriteLine("Square of the given number is " + result2);
Console.WriteLine("Square of the given number is " + result3);
}
}

Here, we have accessed the variable and changed its value from 6 to 7. Then the output is printed after initializing the value to the new variable result 3.

Output:

Objects in C#

Till here, we have created an object and referenced it through a single text format. Now let us see what if we require an array of objects to store and manipulate our data.

Code:

using System;
class Square
{
public int Side;
public void Sqr(int side)
{
Side=side;
}
public int Sq()
{
return Side*Side;
}
}
class First
{
static void Main(String [] args)
{
int result1,result2,result3;
Square[] sq = new Square[3];
sq[0]= new Square();
sq[1]= new Square();
sq[2]= new Square();
sq[0].Side=13;
sq[1].Side=85;
sq[2].Side=25;
result1=sq[0].Sq();
result2=sq[1].Sq();
result3=sq[2].Sq();
Console.WriteLine("Square of the given number is " + result1);
Console.WriteLine("Square of the given number is " + result2);
Console.WriteLine("Square of the given number is " + result3);
}
}

In the above program, the same as before, we have created an array of objects and assigned a value to each object. We then executed our second function to generate the square of two numbers.

Output:

Objects in C#

As an exercise, can you try loading in marks of 5 students in 3 subjects using an array of the object?

Conclusion

As seen above, we have successfully created an object in different ways and used it to assign values to variables and call the functions present inside the class. But here, we need to understand and follow a few rules based on the access modifiers. An object cannot access variables/functions with a “private” access modifier that belongs to another class. But can access the same class variables or functions though declared with a private modifier. So, this way, there are a set of rules that are defined with respect to classes, variables, functions, and objects. Try playing around in creating objects in different ways with different access modifiers and check out the outputs for getting to know the scope of objects and keep learning.

The above is the detailed content of Objects in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Developing with C# .NET: A Practical Guide and ExamplesDeveloping with C# .NET: A Practical Guide and ExamplesMay 12, 2025 am 12:16 AM

C# and .NET provide powerful features and an efficient development environment. 1) C# is a modern, object-oriented programming language that combines the power of C and the simplicity of Java. 2) The .NET framework is a platform for building and running applications, supporting multiple programming languages. 3) Classes and objects in C# are the core of object-oriented programming. Classes define data and behaviors, and objects are instances of classes. 4) The garbage collection mechanism of .NET automatically manages memory to simplify the work of developers. 5) C# and .NET provide powerful file operation functions, supporting synchronous and asynchronous programming. 6) Common errors can be solved through debugger, logging and exception handling. 7) Performance optimization and best practices include using StringBuild

C# .NET: Understanding the Microsoft .NET FrameworkC# .NET: Understanding the Microsoft .NET FrameworkMay 11, 2025 am 12:17 AM

.NETFramework is a cross-language, cross-platform development platform that provides a consistent programming model and a powerful runtime environment. 1) It consists of CLR and FCL, which manages memory and threads, and FCL provides pre-built functions. 2) Examples of usage include reading files and LINQ queries. 3) Common errors involve unhandled exceptions and memory leaks, and need to be resolved using debugging tools. 4) Performance optimization can be achieved through asynchronous programming and caching, and maintaining code readability and maintainability is the key.

The Longevity of C# .NET: Reasons for its Enduring PopularityThe Longevity of C# .NET: Reasons for its Enduring PopularityMay 10, 2025 am 12:12 AM

Reasons for C#.NET to remain lasting attractive include its excellent performance, rich ecosystem, strong community support and cross-platform development capabilities. 1) Excellent performance and is suitable for enterprise-level application and game development; 2) The .NET framework provides a wide range of class libraries and tools to support a variety of development fields; 3) It has an active developer community and rich learning resources; 4) .NETCore realizes cross-platform development and expands application scenarios.

Mastering C# .NET Design Patterns: From Singleton to Dependency InjectionMastering C# .NET Design Patterns: From Singleton to Dependency InjectionMay 09, 2025 am 12:15 AM

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C# .NET in the Modern World: Applications and IndustriesC# .NET in the Modern World: Applications and IndustriesMay 08, 2025 am 12:08 AM

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

C# .NET Framework vs. .NET Core/5/6: What's the Difference?C# .NET Framework vs. .NET Core/5/6: What's the Difference?May 07, 2025 am 12:06 AM

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools