Question

What are the differences between value types and reference types in C#? support your answer with...

What are the differences between value types and reference types in C#? support your answer with examples.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Value types - Th value type is a data type which store the value in its own memory, means the variable in Value type directly contain their value.

For eg - int x= 50;

the system store 50 in the memory allocated for x variable , basically the memory that is given to x will have value 50 stored in it .

Example -

static void valueChange(int i)//it get value of i as 50
{
    i =  100;//i is initialized as 100

    Console.WriteLine(i);//print 100
}

static void Main(string[] args)
{
    int x = 50;

    Console.WriteLine(x); //PRINT 50
    
    valueChange(x);//PASS 50 TO FUNCTION valueChange 
    
    Console.WriteLine(x);//it will again print 50
}

Output -

50

100

50

whereas in Reference type - Reference type does not the value directly in the memory , instead of this it stores the address of where the value is stored in memory . Reference type basically contains a pointer to another memory location that holds the data.

static void changeValue(Car c2)//it point to same address where "BMW" is stored
{
    c2.carNAME = "Audi";//change it value to "Audi" at address where "BMW" was stored
}

static void Main(string[] args)
{
    Car c1= new Car();//initialize object 
    c1.carName= "BMW";//carName memory point to where "BMW" value is stored
    
    changeValue(c1);//pass it to function

    Console.WriteLine(c1.carName); //print Audi as OUTPUT
}

Output - Audi

Add a comment
Know the answer?
Add Answer to:
What are the differences between value types and reference types in C#? support your answer with...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT