readonly is resolved at run time. const is resolved at compile time. Use readonly when you don't know the value until you have to use it. Use const when the value is known and will never change throughout the lifecycle of the system.
Examples:
public class ConstExample
{
public const int example = 1;
public const String anotherExample = 2; //will fail compilation
}
System.out.println(ConstExample.example);
System.out.println(ConstExample.anotherExample);
public class ReadonlyExample
{
public readonly int example = 1;
public readonly int anotherExample;
public ReadonlyExample(String value)
{
anotherExample = Int.parse(value);//if value is not an int, this will not throw an error until runtime
}
}
System.out.println(ReadonlyExample.example);//prints 1
System.out.println(new ReadonlyExample("x").anotherExample);//won't fail until compile time
System.out.println(new ReadonlyExample("5").anotherExample);//will run fine
Advantages and disadvantages are very clear:
- For readonly
- Value can be set at runtime so a developer does not have to worry about knowing the real value ahead of time
- Can be used for mutable objects
- More flexibility
- Can be have different values for each instantiation of the class
- const can only be used for int and String types
- For const
- Performance
- Maintenance (much easier to make a mistake with readonly if the attribute gets an unexpected value set at runtime)
- Must be used with enums
No comments:
Post a Comment