C# Sharp Exercises: When a structure and a class instance is passed to a method
C# Sharp STRUCTURE: Exercise-5 with Solution
Write a program in C# Sharp to show what happen when a structure and a class instance is passed to a method.
Sample Solution:-
C# Sharp Code:
using System;
class newClass
{
public int n;
}
struct newStruct
{
public int n;
}
class strucExer5
{
public static void trackStruct(newStruct st)
{
st.n = 8;
}
public static void tracClass(newClass cl)
{
cl.n = 8;
}
public static void Main()
{
Console.Write("\n\nWhen a structure and a class instance is passed to a method :\n");
Console.Write("--------------------------------------------------------------\n");
newStruct ns = new newStruct();
newClass nc = new newClass();
ns.n = 5;
nc.n = 5;
//value of the struct field did not changed by passing its instance
//because a copy of the struct was passed to the trackStruct method
trackStruct(ns);
//value of the class field changed by passing its instance
//because a reference to the class was passed to the tracClass method
tracClass(nc);
Console.WriteLine("\nns.n = {0}", ns.n);
Console.WriteLine("nc.n = {0}\n", nc.n);
}
}
Sample Output:
When a structure and a class instance is passed to a method : -------------------------------------------------------------- ns.n = 5 nc.n = 8
Flowchart:
C# Sharp Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a program in C# Sharp to create a structure and assign the value and call it.
Next: Write a program in C# Sharp to declares a struct with a property, a method, and a private field.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework