0
0
C Sharp (C#)programming~20 mins

Passing value types to methods in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Value Type Passing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of passing value type to method
What is the output of the following C# code?
C Sharp (C#)
using System;
class Program {
    static void Increment(int x) {
        x = x + 1;
    }
    static void Main() {
        int a = 5;
        Increment(a);
        Console.WriteLine(a);
    }
}
A5
B6
CCompilation error
DRuntime error
Attempts:
2 left
💡 Hint
Remember that value types are passed by value by default.
Predict Output
intermediate
2:00remaining
Effect of ref keyword on value type parameter
What will be printed by this C# program?
C Sharp (C#)
using System;
class Program {
    static void Increment(ref int x) {
        x = x + 1;
    }
    static void Main() {
        int a = 5;
        Increment(ref a);
        Console.WriteLine(a);
    }
}
A6
B5
CCompilation error
DRuntime error
Attempts:
2 left
💡 Hint
The ref keyword passes the variable by reference.
🔧 Debug
advanced
2:00remaining
Identify the error when passing value type without ref
What error will this code produce?
C Sharp (C#)
using System;
class Program {
    static void Increment(ref int x) {
        x = x + 1;
    }
    static void Main() {
        int a = 5;
        Increment(a);
        Console.WriteLine(a);
    }
}
ANo error, output is 6
BRuntime error: NullReferenceException
CCompile-time error: argument must be passed with 'ref'
DCompile-time error: method not found
Attempts:
2 left
💡 Hint
Check how ref parameters must be called.
Predict Output
advanced
2:00remaining
Passing struct value type to method and modifying fields
What is the output of this C# program?
C Sharp (C#)
using System;
struct Point {
    public int X;
    public int Y;
}
class Program {
    static void Move(Point p) {
        p.X += 10;
        p.Y += 10;
    }
    static void Main() {
        Point pt = new Point { X = 1, Y = 1 };
        Move(pt);
        Console.WriteLine($"{pt.X}, {pt.Y}");
    }
}
A11, 11
BRuntime error
CCompilation error
D1, 1
Attempts:
2 left
💡 Hint
Structs are value types and passed by value by default.
Predict Output
expert
2:00remaining
Passing value type with out parameter
What will be the output of this C# program?
C Sharp (C#)
using System;
class Program {
    static void Initialize(out int x) {
        x = 10;
    }
    static void Main() {
        int a;
        Initialize(out a);
        Console.WriteLine(a);
    }
}
ACompilation error: variable 'a' used uninitialized
B10
C0
DRuntime error: variable 'a' used before assignment
Attempts:
2 left
💡 Hint
Out parameters must be assigned inside the method before use.