Tech
Forums
Jobs
Books
Events
Interviews
Live
More
Learn
Training
Career
Members
Videos
News
Blogs
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
Difference Between Constant And ReadOnly
WhatsApp
Satish Kumar Vadlavalli
8y
63.1
k
0
5
25
Blog
Constants
Constants are static by default.
They must have a value at compilation-time (you can have e.g. 3.14 * 2 + 5, but cannot call methods).
Could be declared within functions.
These are copied into every assembly that uses them (every assembly gets a local copy of values).
using
System;
namespace
ConstantExample
{
class
ConstantExample
{
private
const
int
PI = 3.14;
public
static
void
Main()
{
//You have to initialize Const variables while declaration
const
int
RollNo = 1284;
//Valid scenario
const
int
Age = 10 + 13;
const
string
Name =
"Satish Kumar"
;
// Reassigning a const variable is not allowed.
RollNo = 1405;
// Will result compile time error.
Age++;
// Will result compile time error.
Console.WriteLine(Name);
Console.Read();
}
}
}
Readonly
Must have set value, by the time constructor exits.
Are evaluated when instance is created.
You can use static modifier for readonly fields.
readonly modifier can be used with reference types.
readonly modifier can be used only for instance or static fields, you cannot use readonly keyword for variables in the methods.
using
System;
namespace
ReadOnlyExample
{
class
ReadOnlyTest
{
//You have to initilize readonly varabiles while declaration or in constructor
readonly
int
RollNo = 1284;
//Valid scenario
readonly
int
Age;
readonly
string
Name =
"Satish Kumar"
;
//readonly fields can be initlized in constructor
public
ReadOnlyTest (
string
name)
{
Age = 23;
Name =
name
;
}
public
changeName(
string
newName)
{
Name =
"Satish Kumar Vadlavalli"
; ;
// Will result error.
}
}
class
ReadOnlyExample
{
public
static
void
Main()
{
ReadOnlyTest obj =
new
ReadOnlyTest(
"Satish"
);
Console.Read();
}
}
}
Difference between const and readonly
const fields has to be initialized while declaration only, while readonly fields can be initialized at declaration or in the constructor.
const variables can declared in methods ,while readonly fields cannot be declared in methods.
const fields cannot be used with static modifier, while readonly fields can be used with static modifier.
A const field is a compile-time constant, the readonly field can be used for run time constants.
A blog without comments is not a blog at all, but do try to stay on topic. Please comment if you have any questions or leave your valuable feedback. Happy Learning.
C#
Constant
ReadOnly
Up Next
Constant VS ReadOnly
Ebook Download
View all
Programming Strings using C#
Read by 23.4k people
Download Now!
Learn
View all
Membership not found