In my case , I have bunch of values of same type , let's say floats :
float value1 = 1.2f;
float value2 = 1.5f;
float value3 = 2.3f;
Now I need a pointer or a reference value can get a instance of this floats and do operations on it.
in C++ :
float* float_reference;
Now I want to set float_reference to value1
So in my functions every computation put result in value1.
Notes : - I don't want to use classes - I don't want to use ref keyword in a functions - I don't want to use unsafe keyword
I just need to do it as I said like C++ , Is there any other way around ?
EDIT 1 : This is why I can't use unsafe , Here's Example :
using System.Windows;
namespace ValueUpdater
{
public unsafe partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//// need to assign one of floats to reference object
}
float value1 = 1.2f;
float value2 = 1.5f;
float value3 = 2.3f;
float* value_ref; ////// Can't Make this pointer!
private void Button_Click(object sender, RoutedEventArgs e)
{
/// Need to change the reference here
fixed (float* value_ref = &value3) {
*value_ref += 2;
};
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
/// Need to change the reference here
/// But can't use value_ref = &value3 without re-initalize
fixed (float* value_ref = &value3)
{
*value_ref -= 2;
};
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
Output.Content = value3.ToString();
}
}
}
XAML :
<Window x:Class="ValueUpdater.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ValueUpdater"
mc:Ignorable="d"
Title="MainWindow" Height="354.017" Width="368.698">
<Grid>
<Button Content="Add 2" Margin="0,28,27,0" VerticalAlignment="Top" HorizontalAlignment="Right" Width="75" Click="Button_Click"/>
<Button Content="Sub 2" Margin="0,55,27,0" VerticalAlignment="Top" HorizontalAlignment="Right" Width="75" Click="Button_Click_1"/>
<Button Content="Reset" Margin="0,83,27,0" VerticalAlignment="Top" HorizontalAlignment="Right" Width="75"/>
<Button Content="Print" Margin="0,0,27,20" HorizontalAlignment="Right" Width="75" Height="20" VerticalAlignment="Bottom" Click="Button_Click_2"/>
<Label x:Name="Output" Content="Output" HorizontalAlignment="Left" Margin="19,22,0,0" VerticalAlignment="Top" Width="182"/>
</Grid>
</Window>
ref floatis the equivalent in C#;ref float float_reference = ref value1;(safe C#) is virtually identical tofloat* float_ptr = &value1;(unsafe C#) - the only difference is that the GC understands the first version, so it doesn't need pinning etc; I'd really love to understand why you don't want to useref, when it is the equivalent code (note:refis usually used with parameters etc, but: ref-locals are a thing)