Note that there are some explanatory texts on larger screens.

plurals
  1. POPassing a generic pointer to a method in c#
    primarykey
    data
    text
    <p>I have created a generic type to act as a pointer so that I can pass by reference. (Perhaps there is a much more simple way of doing this but I want to stress that I am doing this to learn more about generics and passing by reference, not the most efficient way of completing the task, if that makes sense.)</p> <p>Here is the code I wrote for the generic type</p> <pre><code>class GenericPointer&lt;T&gt; { public T item; public void setItem(T i){ item = i; } public T getItem(){ return item; } } </code></pre> <p>In my program I have created an instance of this type called 'intPointer'. The value 143 is arbitrary.</p> <pre><code>GenericPointer&lt;int&gt; intPointer = new GenericPointer&lt;int&gt;(); intPointer.setItem(143); Console.WriteLine(intPointer.getItem()); </code></pre> <p>The above code runs properly, setting and returning the value 143.</p> <p>I now want to pass this 'intPointer' to a method that increments it and then prints the value again.</p> <p>So I wrote a method called addone()</p> <pre><code>public void addone(int i) { i ++; } </code></pre> <p>Now I want to make the following calls (remembering that I already set the value to 143):</p> <pre><code>Console.WriteLine(intPointer.getItem()); addone(intPointer); Console.WriteLine(intPointer.getItem()); </code></pre> <p>What I was expecting to see was 143 then 144 however I get the following errors:</p> <pre><code>The best overloaded method match for 'Notes.Program.addone(int)' has some invalid arguments </code></pre> <p>and:</p> <pre><code>cannot convert from 'Notes.GenericPointer&lt;int&gt;' to 'int' </code></pre> <p>Any help would be greatly appreciated!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload