i know that string is like a class, and when creating a new string the string itself doesnt owe the value but only the value's pointer. but when creating a string there is no need to use the word new;
string a = "hello";
and not
string a = new string("hello");
I know that the second option is also possible but what i want to understand is why the first one?
Let's say I have a class name student which he's constructor gets a string. To create a new class I must use the saved word new.
student example = new student("Sabrina");
I tried overload oparator = but it is not possible.
How can I create a new class like a string does (without using the word new)?
student example = "Sabrina";
You can use cast operator to implicitly:
sealed class Student
{
public string Name
{
get;
private set;
}
Student()
{
}
public static implicit operator Student(string name)
{
return new Student
{
Name = name
};
}
}
Then you can do Student student = "Sabrina";.
Although you can get this done using an implicit operator, I would highly recommend not doing this at all. Strings are special animals in C# and they get special treatment - along with other special classes like int and float, you can create them without explicitly newing them up due to the way the C# compiler works:
var myInt = 0;
var myFloat = 0f;
var myString = "string";
However, this behavior is typically restricted to those special classes. Adding an implicit operator to do this is bad practice for multiple reasons:
It hides what is actually going on underneath. Are we creating a new Student under the hood when converting from a string?
It is unmaintainable. What happens when you have to add another parameter to the constructor to include the Student's ID number as well?
It eliminates the possibility of using implicitly-typed variables. You can't call var student = "name"; you must call Student student = "name".
The implicit operator paradigm breaks down very quickly. Though it's a cool thing to do, you're setting yourself up for a bad time down the road and making your code more difficult to read. I would highly advise just using new Student("name") like all other normal objects in C#.
The string "hello" in your code, in all cases, does not involve a call to a constructor. It is a constant value, created at compile time, such that all instances of the string "hello" are all the same object. Similarly, the integer 1 and decimal value 3.456, and any other "literal" value, are constants that exist before runtime, before the constructor code can have a chance to be called.
The code new string("hello"); cannot be called, as there is no constructor for string that takes a string as a value. However, if you changed it to new string("hello".ToCharArray());, you would get a string object, but it won't be the same thing as the string "hello". You've actually created a new string, at a separate memory location, from just plain "hello". It only just so happens to have the same character values contained in it as "hello".
The significance is that, if you do use the implicit type conversion trick, then one string literal converted to your type will not be the same object:
class Foo
{
private string value;
public Foo(string val)
{
this.value = val;
}
public static implicit operator Foo(string value)
{
return new Foo(value);
}
}
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
Foo a = "asdf";
Foo b = "asdf";
Assert.AreNotEqual(a, b);
}
}
In other words, a.Equals(b) returns false. In order to make the Equals method return true, you'll have to override the Equals method in your Foo class.
public override bool Equals(object obj)
{
return obj is Foo && value.Equals(((Foo)obj).value);
}
But, as mentioned by other posters, this is an obfuscation. You'll make it difficult to use the code as well as difficult to debug it. It changes what looks like a regular assignment to a full method call. And it breaks many of the tools that Visual Studio provides for inspecting code, such as F12 to jump to a method definition.
Implicit type conversion should be used only in cases where the two types are actually quite interchangeable in use, with minor differences in their functionality. The float type can implicitly convert to double because there are no extra methods and functions for double vs float, and increasing the precision from float to double does not change the value. However, going from double to float requires an explicit cast, because the loss of precision changes the value represented.
You could have a method named createObject() and use that while having the constructors private, discourage their use.
Related
Perhaps I am demonstrating my ignorance of some oft-used feautre of C# or the .NET framework, but I would like to know if there is a natively-supported way to create a type alias like EmailAddress which aliases string but such that I can extend it with my own methods like bool Validate()?
I know of the using x = Some.Type; aliases but these are not global nor do they provide type safety, i.e. one could swap out an ordinary string for the using alias in the current file. I would like my EmailAddress to be its own type, independent and not interchangeable with the string type that it shadows.
My current solution is to generate public sealed partial EmailAddress : IEquatable<EmailAddress>, IXmlSerializable classes with a T4 template generating the boilerplate implicit string conversion operators and other such things. This is fine with me for now and gives me a lot of flexibility but at the back of my mind it seems silly that I have to generate such copious amounts of boilerplate code to do something as simple as creating a strong type alias.
Maybe this is not possible other than with code generation, but I am curious if others have attempted something similar with their designs and what your experiences have been. If nothing else, perhaps this could serve as a good use-case for such an alias feature in a hypothetical future version of C#. Thanks!
EDIT: The real value that I want out of this is to be able to get type safety with primitive types that represent different types/formats for data. For instance, an EmailAddress and a SocialSecurityNumber and a PhoneNumber, all of which use string as their underlying type but which are not interchangeable types in and of themselves. I think this gets you much more readable and self-documenting code, not to mention added benefits of more method overload possibilities that are less ambiguous.
If you look at the .NET Framework System.Uri is the closest example that is similar to an email address. In .NET the pattern is to wrap something in a class and add constraints that way.
Adding strong typing that adds additional constraints to simple types is an interesting language feature that I believe some functional language has. I can't recall the name of the language which would let you add dimensional units such as feet to your values and do a dimensional analysis on your equations to ensure that the units matched.
Some background on why string is sealed:
From http://www.code-magazine.com/Article.aspx?quickid=0501091 :
Rory: Hey Jay, you mind if I ask you a
couple questions? I'm already curious
about some things. First of all, and
this was brought up at one of the MSDN
events I did this week, why is String
sealed? Note: for VB.NET programmers,
Sealed = NotInheritable.
Jay: Because we do a lot of magic
tricks in String to try and make sure
we can optimize for things like
comparisons, to make them as fast as
we possibly can. So, we're stealing
bits off of pointers and other things
in there to mark things up. Just to
give you an example, and I didn't know
this when I started, but if a String
has a hyphen or an apostrophe in it
[then] it sorts differently than if it
just has text in it, and the algorithm
for sorting it if you have a hyphen or
an apostrophe if you're doing
globally-aware sorting is pretty
complicated, so we actually mark
whether or not the string has that
type of behavior in it.
Rory: So, what you're saying is that
in the string world, if you didn't
seal String there would be a whole lot
of room for wreaking a lot of havoc if
people were trying to subclass it.
Jay: Exactly. It would change the
entire layout of the object, so we
wouldn't be able to play the tricks
that we play that pick up speed.
Here is the CodeProject article that you probably have seen before:
http://www.codeproject.com/KB/cs/expandSealed.aspx
So yeah, implicit operator is your only solution.
Does the System.Net.Mail.MailAddress class fit your needs, or at least "help"?
EDIT: It's not explicitly IEquatable or ISerializable, but you could easily enough add those in your own wrapper.
It seems you have at least a reasonable C# knoledgde so my answer may seem stupid, but what you want is called "type hierarchy" and the guys who coded the String class wanted to prevent you from using this "OO feature" so they made String class sealed, that's why you won't be able to do what you want. The best approach is this you are on now: Make your own type and an implicit convertion to String.
I think you want to use extension methods. They allow you to extend a classes functionality without creating a new derived type.
I guess I do not get why you want to have both strong types AND implicit string conversion at the same time. For me, one rules out the other.
I tried to solve the same problem for ints (you mention int in the title, but not in the question). I found that declaring an enum gives you a type-safe integer which needs to be explicitly cast from/to int.
Update
Enums may not be intended for open sets, but can still be used in such a way. This sample is from a compilation experiment to distinguish between the ID columns of several tables in a database:
enum ProcID { Unassigned = 0 }
enum TenderID { Unassigned = 0 }
void Test()
{
ProcID p = 0;
TenderID t = 0; <-- 0 is assignable to every enum
p = (ProcID)3; <-- need to explicitly convert
if (p == t) <-- operator == cannot be applied
t = -1; <-- cannot implicitly convert
DoProc(p);
DoProc(t); <-- no overloaded method found
DoTender(t);
}
void DoProc(ProcID p)
{
}
void DoTender(TenderID t)
{
}
I made this class to cover identical needs. This one is for the type "int" (I also have one for "string"):
public class NamedInt : IComparable<int>, IEquatable<int>
{
internal int Value { get; }
protected NamedInt() { }
protected NamedInt(int val) { Value = val; }
protected NamedInt(string val) { Value = Convert.ToInt32(val); }
public static implicit operator int (NamedInt val) { return val.Value; }
public static bool operator ==(NamedInt a, int b) { return a?.Value == b; }
public static bool operator ==(NamedInt a, NamedInt b) { return a?.Value == b?.Value; }
public static bool operator !=(NamedInt a, int b) { return !(a==b); }
public static bool operator !=(NamedInt a, NamedInt b) { return !(a==b); }
public bool Equals(int other) { return Equals(new NamedInt(other)); }
public override bool Equals(object other) {
if ((other.GetType() != GetType() && other.GetType() != typeof(string))) return false;
return Equals(new NamedInt(other.ToString()));
}
private bool Equals(NamedInt other) {
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(Value, other.Value);
}
public int CompareTo(int other) { return Value - other; }
public int CompareTo(NamedInt other) { return Value - other.Value; }
public override int GetHashCode() { return Value.GetHashCode(); }
public override string ToString() { return Value.ToString(); }
}
And to consume it in your case:
public class MyStronglyTypedInt: NamedInt {
public MyStronglyTypedInt(int value) : base(value) {
// Your validation can go here
}
public static implicit operator MyStronglyTypedInt(int value) {
return new MyStronglyTypedInt(value);
}
public bool Validate() {
// Your validation can go here
}
}
If you need to be able to serialize it (Newtonsoft.Json), let me know and I'll add the code.
I have a class with an implicit conversion from string defined as:
class TestClass : ITestInterface
{
public static implicit operator TestClass(string value)
{
return new TestClass(value);
}
public TestClass(string value)
{
Value = value;
}
public string Value { get; set; }
}
It implements a marker interface:
public interface ITestInterface { }
I have a method of another class defined as:
public void DoSomething(ITestInterface thing) { }
I'm getting an error trying to call that method:
public void Test()
{
TestClass a = "This works fine.";
DoSomething("Why doesn't this work?");
}
cannot convert from 'string' to 'Tests.ITestInterface'
All code is greatly simplified; my actually requirements are far more complex, but this seems to be the core of what is blocking the pattern I'd like to implement.
What is preventing this from working? (Something in the C# spec?)
Are there any changes I can make to my code to allow this type of casting to work?
You're omitting the third option that explains the issue:
//1
TestClass a = "This works fine.";
//2
ITestInterface i = "This doesn't work either!";
//3
DoSomething("Why doesn't this work?");
In (1), you've declared TestClass a. This means that the compiler knows that when you use a different type (string, in this case), that it should try to convert said value to TestClass.
In (2), you've declared ITestInterface i. This means that the compiler knows that when you use a different type (string, in this case), that it should try to convert said value to ITestInterface.
That is the source of the problem. There is no conversion defined between string and ITestInterface.
What you're currently thinking is:
Well, I know that I want this to be converted to a TestClass. Why doesn't the compiler figure out what I want it to do?
The short answer to that is that the compiler refuses to guess.
What you want to happen would lead to impossible situations. For example, what would happen if there was a second class which also implements ITestInterface?
class SecondTestClass: ITestInterface
{
public static implicit operator SecondTestClass(string url)
{
return new SecondTestClass(url);
}
public SecondTestClass(string url)
{
Value = GetValueFromTheInternet(url);
}
public string Value { get; set; }
}
Let's re-evaluate your code:
//1
TestClass a = "This works fine.";
This works. There is a conversion from string to TestClass.
//2
SecondTestClass b = "This works fine.";
This works. There is a conversion from string to SecondTestClass.
//3
ITestInterface i = "This still doesn't work!";
//4
DoSomething("This doesn't work for the same reason as //3");
This doesn't work. The compiler does not have any known conversion from string to ITestInterface.
The compiler is unable to figure out if you want this to be converted to a TestClass and then assigned to i, or if you want this to be converted to a SecondTestClass and then assigned to i.
And, as I said before, the compiler refuses to guess.
Also, just for clarity, this would work:
TestClass a = "This works fine.";
ITestInterface i1 = a;
DoSomething(a);
DoSomething(i1);
SecondTestClass b = "This works fine.";
ITestInterface i2 = b;
DoSomething(b);
DoSomething(i2);
All of these assignations work.
The crux of your problem is that the compiler wants you to explicitly state which type you want the string to be converted to. In your own example, you were already explicitly asking for a TestClass. Notice that this would not have worked if you had used var, as the compiler would not be able to figure it out in that case either.
Pretty clear from the compiler-error, isn´t it? DoSomething expects an instance of ITestInterface, which string does not implement. The fact that there is an implicit conversion from string to your class doesn´t make this conversion also applicable for any other class implementing the interface.
Imagine there was another class implementing the interface:
class AnotherTestClass : ITestInterface { }
how would the DoSomething-call now be resolved? To which class should the conversion apply? To an instance of TestClass or to AnotherTestClass? In particular if AnotherClass also has an implicit cast-operator defined. That´s why this does not work.
Or consider the other way round: when you have only the interface but no class at all that implements it (which is pretty common when you design an API), there is no conversion at all. Your design introduces some static binding from an interface to a concrete implementation of it, which is a bad thing. In fact that makes your DoSomething-method only work for instances of type TestClass, which contradicts the use of an interface as parameter. So however uses your API can use only ever provide an instance of TestClass to your method.
Apart from this I doubt a cast is a good thing here. By having an implicit concversion you imply that every string can safely be converted to your class without losing any information. E.g. is an URI a valid representation of your class? Or even your provided "Why doesn't this work?"?
On the other side a constructor that expects a string is far more precise and makes it clear:
var m = new TestClass(myString);
From my experience there are only some very few cases where you really need an implicit cast. What you do far more often is to create some instance based upon some input and append some more data to that instance. In your example that means that a TestClass consists of some string-information, but may also have some more data.
public void DoSomething(ITestInterface thing) { }
Because the parameter is an interface and you want to call static implicit operator TestClass(string value) but it is impossible. The interface in C# can not have static method.
You can pass a class TestClass as a parameter only
public static void DoSomething(TestClass thing) { Console.WriteLine(thing.Value); }
Ok so lets say I have a structure A like that:
Struct A{
private String _SomeText;
private int _SomeValue;
public A(String someText, int SomeValue) { /*.. set the initial values..*/ }
public String SomeText{ get { return _SomeText; } }
public int SomeValue{ get { return _SomeValue; } }
}
Now what I want to be able to do is to return that Structure A as a result of a method in a Class ABC, like that:
Class ABC{
public A getStructA(){
//creation of Struct A
return a;
}
}
I don't want any programmer using my library (which will have Struct A and Class ABC and some more stuff) to ever be able to create an instance of Struct A.
I want the only way for it to be created is as a return from the getStructA() method. Then the values can be accessed through the appropriate getters.
So is there any way to set a restrictions like that? So a Structure can't be instantiated outside of a certain class? Using C#, .Net4.0.
Thanks for your help.
---EDIT:----
To add some details on why am I trying to achieve this:
My class ABC has some "status" a person can query. This status has 2 string values and then a long list of integers.
There never will be a need to create an object/instance of "Status" by the programmer, the status can only be returned by "getStatus()" function of the class.
I do not want to split these 3 fields to different methods, as to obtain them I am calling Windows API (p/invoke) which returns similar struct with all 3 fields.
If I was indeed going to split it to 3 methods and not use the struct, I would have to either cache results or call the method from Windows API every time one of these 3 methods is called...
So I can either make a public struct and programmers can instantiate it if they want, which will be useless for them as there will be no methods which can accept it as a parameter. Or I can construct the library in such a way that this struct (or change it to a class if it makes things easier) can be obtained only as a return from the method.
If the "restricted" type is a struct, then no, there is no way to do that. The struct must be at least as public as the factory method, and if the struct is public then it can be constructed with its default constructor. However, you can do this:
public struct A
{
private string s;
private int i;
internal bool valid;
internal A(string s, int i)
{
this.s = s;
this.i = i;
this.valid = true;
}
...
and now you can have your library code check the "valid" flag. Instances of A can only be made either (1) by a method internal to your library that can call the internal constructor, or (2) by the default constructor. You can tell them apart with the valid flag.
A number of people have suggested using an interface, but that's a bit pointless; the whole point of using a struct is to get value type semantics and then you go boxing it into an interface. You might as well make it a class in the first place. If it is going to be a class then it is certainly possible to make a factory method; just make all the ctors of the class internal.
And of course I hope it goes without saying that none of this gear should be used to implement code that is resistant to attack by a fully-trusted user. Remember, this system is in place to protect good users from bad code, not good code from bad users. There is nothing whatsoever that stops fully trusted user code from calling whatever private methods they want in your library via reflection, or for that matter, altering the bits inside a struct with unsafe code.
Create a public interface and make the class private to the class invoking it.
public ISpecialReturnType
{
String SomeText{ get; }
int SomeValue{ get; }
}
class ABC{
public ISpecialReturnType getStructA(){
A a = //Get a value for a;
return a;
}
private struct A : ISpecialReturnType
{
private String _SomeText;
private int _SomeValue;
public A(String someText, int SomeValue) { /*.. set the initial values..*/ }
public String SomeText{ get { return _SomeText; } }
public int SomeValue{ get { return _SomeValue; } }
}
}
What exactly are you concerned about? A structure is fundamentally a collection of fields stuck together with duct tape. Since struct assignment copies all of the fields from one struct instance to another, outside the control of the struct type in question, structs have a very limited ability to enforce any sort of invariants, especially in multi-threaded code (unless a struct is exactly 1, 2, or 4 bytes, code that wants to create an instance which contains a mix of data copied from two different instances may do so pretty easily, and there's no way the struct can prevent it).
If you want to ensure that your methods will not accept any instances of a type other than those which your type has produced internally, you should use a class that either has only internal or private constructors. If you do that, you can be certain that you're getting the instances that you yourself produced.
EDIT
Based upon the revisions, I don't think the requested type of restriction is necessary or particularly helpful. It sounds like what's fundamentally desired to stick a bunch of values together and store them into a stuck-together group of variables held by the caller. If you declare a struct as simply:
public struct QueryResult {
public ExecutionDuration as Timespan;
public CompletionTime as DateTime;
public ReturnedMessage as String;
}
then a declaration:
QueryResult foo;
will effectively create three variables, named foo.ExecutionDuration, foo.CompletionTime, and foo.ReturnedMessage. The statement:
foo = queryPerformer.performQuery(...);
will set the values of those three variables according to the results of the function--essentially equivalent to:
{
var temp = queryPerformer.performQuery(...);
foo.ExecutionDuration = temp.ExecutionDuration
foo.CompletionTime = temp.CompletionTime;
foo.ReturnedMessage = temp.ReturnedMessage;
}
Nothing will prevent user code from doing whatever it wants with those three variables, but so what? If user code decides for whatever reason to say foo.ReturnedMessage = "George"; then foo.ReturnedMessage will equal George. The situation is really no different from if code had said:
int functionResult = doSomething();
and then later said functionResult = 43;. The behavior of functionResult, like any other variable, is to hold the last thing written to it. If the last thing written to it is the result of the last call to doSomething(), that's what it will hold. If the last thing written was something else, it will hold something else.
Note that a struct field, unlike a class field or a struct property, can only be changed either by writing to it, or by using a struct assignment statement to write all of the fields in one struct instance with the values in corresponding fields of another. From the consumer's perspective, a read-only struct property carries no such guarantee. A struct may happen to implement a property to behave that way, but without inspecting the code of the property there's no way to know whether the value it returns might be affected by some mutable object.
I'm using a 3rd party's set of webservices, and I've hit a small snag. Before I manually make a method copying each property from the source to the destination, I thought I'd ask here for a better solution.
I've got 2 objects, one of type Customer.CustomerParty and one of type Appointment.CustomerParty. The CustomerParty objects are actually property and sub-oject exactly the same. But I can't cast from 1 to the other.
So, I need to find a certain person from the webservice. I can do that by calling Customer.FindCustomer(customerID) and it returns a Customer.CustomerParty object.
I need to take that person that I found and then use them a few lines down in a "CreateAppointment" request. Appointment.CreateAppointment takes an appointment object, and the appointment object contains a CustomerParty object.
However, the CustomerParty object it wants is really Appointment.CustomerParty. I've got a Customer.CustomerParty.
See what I mean? Any suggestions?
Why don't you use AutoMapper? Then you can do:
TheirCustomerPartyClass source = WebService.ItsPartyTime();
YourCustomerPartyClass converted =
Mapper.Map<TheirCustomerPartyClass, YourCustomerPartyClass>(source);
TheirCustomerPartyClass original =
Mapper.Map<YourCustomerPartyClass, TheirCustomerPartyClass>(converted);
As long as the properties are identical, you can create a really simple map like this:
Mapper.CreateMap<TheirCustomerPartyClass, YourCustomerPartyClass>();
Mapper.CreateMap<YourCustomerPartyClass, TheirCustomerPartyClass>();
This scenario is common when writing domain patterns. You essentially need to write a domain translator between the two objects. You can do this several ways, but I recommend having an overridden constructor (or a static method) in the target type that takes the service type and performs the mapping. Since they are two CLR types, you cannot directly cast from one to the other. You need to copy member-by-member.
public class ClientType
{
public string FieldOne { get; set; }
public string FieldTwo { get; set; }
public ClientType()
{
}
public ClientType( ServiceType serviceType )
{
this.FieldOne = serviceType.FieldOne;
this.FieldTwo = serviceType.FieldTwo;
}
}
Or
public static class DomainTranslator
{
public static ServiceType Translate( ClientType type )
{
return new ServiceType { FieldOne = type.FieldOne, FieldTwo = type.FieldTwo };
}
}
I'm using a 3rd party's set of
webservices...
Assuming you can't modify the classes, I'm not aware of any way you can change the casting behavior. At least, no way that isn't far, far more complicated than just writing a CustomerToAppointmentPartyTranslator() mapping function... :)
Assuming you're on a recent version of C# (3.5, I believe?), this might be a good candidate for an extension method.
Have you looked at adding a conversion operator to one of the domain classes to define an explicit cast. See the msdn documentation here.
Enjoy!
A simple and very fast way of mapping the types is using the PropertyCopy<TTarget>.CopyFrom<TSource>(TSource source)
method from the MiscUtil library as described here:
using MiscUtil.Reflection;
class A
{
public int Foo { get; set; }
}
class B
{
public int Foo { get; set; }
}
class Program
{
static void Main()
{
A a = new A();
a.Foo = 17;
B b = PropertyCopy<B>.CopyFrom(a);
bool success = b.Foo == 17; // success is true;
}
}
Two classes with exactly the same signature, in two different namespaces, are two different classes. You will not be able to implicitly convert between them if they do not explicitly state how they can be converted from one to the other using implicit or explicit operators.
There are some things you may be able to do with serialization. WCF DataContract classes on one side do not have to be the exact same type as the DataContract on the other side; they just have to have the same signature and be decorated identically. If this is true for your two objects, you can use a DataContractSerializer to "convert" the types through their DataContract decoration.
If you have control over the implementation of one class or the other, you can also define an implicit or explicit operator that will define how the other class can be converted to yours. This will probably simply return a new reference of a deep copy of the other object in your type. Because this is the case, I would define it as explicit, to make sure the conversion is only performed when you NEED it (it will be used in cases when you explicitly cast, such as myAppCustomer = (Appointment.CustomerParty)myCustCustomer;).
Even if you don't control either class, you can write an extension method, or a third class, that will perform this conversion.
I'd like semantics similar to C#'s ref keyword.
Java is confusing because everything is passed by value. However for a parameter of reference type (i.e. not a parameter of primitive type) it is the reference itself which is passed by value, hence it appears to be pass-by-reference (and people often claim that it is). This is not the case, as shown by the following:
Object o = "Hello";
mutate(o)
System.out.println(o);
private void mutate(Object o) { o = "Goodbye"; } //NOT THE SAME o!
Will print Hello to the console. The options if you wanted the above code to print Goodbye are to use an explicit reference as follows:
AtomicReference<Object> ref = new AtomicReference<Object>("Hello");
mutate(ref);
System.out.println(ref.get()); //Goodbye!
private void mutate(AtomicReference<Object> ref) { ref.set("Goodbye"); }
Can I pass parameters by reference in
Java?
No.
Why ? Java has only one mode of passing arguments to methods: by value.
Note:
For primitives this is easy to understand: you get a copy of the value.
For all other you get a copy of the reference and this is called also passing by value.
It is all in this picture:
In Java there is nothing at language level similar to ref. In Java there is only passing by value semantic
For the sake of curiosity you can implement a ref-like semantic in Java simply wrapping your objects in a mutable class:
public class Ref<T> {
private T value;
public Ref(T value) {
this.value = value;
}
public T get() {
return value;
}
public void set(T anotherValue) {
value = anotherValue;
}
#Override
public String toString() {
return value.toString();
}
#Override
public boolean equals(Object obj) {
return value.equals(obj);
}
#Override
public int hashCode() {
return value.hashCode();
}
}
testcase:
public void changeRef(Ref<String> ref) {
ref.set("bbb");
}
// ...
Ref<String> ref = new Ref<String>("aaa");
changeRef(ref);
System.out.println(ref); // prints "bbb"
From James Gosling in "The Java Programming Language":
"...There is exactly one parameter passing mode in Java - pass by value - and that keeps things simple.
.."
I don't think you can. Your best option might be to encapsulate the thing you want to pass "by ref" onto another class instance, and pass the (outer) class's reference (by value). If you see what I mean...
i.e. your method changes the internal state of the object it is passed, which is then visible to the caller.
Java is always pass by value.
When you pass a primitive it's a copy of the value, when you pass an object it's a copy of the reference pointer.
Another option is to use an array, e.g.
void method(SomeClass[] v) { v[0] = ...; }
but 1) the array must be initialized before method invoked, 2) still one cannot implement e.g. swap method in this way...
This way is used in JDK, e.g. in java.util.concurrent.atomic.AtomicMarkableReference.get(boolean[]).
Check out my response in: http://stackoverflow.com/a/9324155/1676736
In there I used a simpler version of the wrapper class idea.
I don't like setters/getters as a standard. When there is no reason to bury a field I make it 'public'. Especially in something like this.
However, this would work for all but the primitive, or multi-parameter/type returns:
public class Ref<T> {
public T val;
}
Although, I suppose you could just add more type parameters. But I think that creating an inner static class fit-for-purpose would be easier:
public static class MyReturn {
public String name;
public int age;
public double salary;
}
this would be for use when you don't need it for other reasons.
MyReturn mRtn = new MyReturn();
public void myMethod(final MyReturn mRtn){
mRtn.name = "Fred Smith";
mRtn.age = 32;
mRtn.salary = 100000.00;
}
System.out.println(mRtn.name + " " +mRtn.age + ": $" + mRtn.salary);