In the program I'm writing I have a class that has a public byte array in it that I want to access and use.
class HasByte
{
public byte[] theByteArray = new byte[4];
public HasByte(IPAddress someAddress)
{
theByteArray = someAddress.GetAddressBytes();
}
}
class WantsByte
{
IPAddress address = IPAddress.Parse("192.168.1.1");
HasByte theInstance = new HasByte(address);
//do something with theInstance.theByteArray[2] for example
}
Currently, the byte array I access through theInstance.theByteArray is all 0's for some reason that I would like to know.
Thanks.
In your class WantsByte
you are trying to initialize member theInstance
via another non-static member address
and compiler must be complaining with Error CS0236. You can move theInstance
initialization to a constructor:
class WantsByte
{
IPAddress address = IPAddress.Parse("192.168.1.1");
HasByte theInstance;
public WantsByte()
{
theInstance = new HasByte(this.address);
}
}
Demo example:
using System;
using System.Net;
using System.Linq;
public class Program
{
public static void Main()
{
var wants = new WantsByte();
}
}
class HasByte
{
public byte[] theByteArray = new byte[4];
public HasByte(IPAddress someAddress)
{
theByteArray = someAddress.GetAddressBytes();
}
}
class WantsByte
{
IPAddress address = IPAddress.Parse("192.168.1.1");
HasByte theInstance;
public WantsByte()
{
theInstance = new HasByte(this.address);
// do something with theInstance.theByteArray[2] for example
// Let's print all elements of the array
Console.WriteLine(String.Join(",", theInstance.theByteArray.Select(o => o.ToString()).ToArray()));
}
}
gives output:
192,168,1,1
Alternatively, in class WantsByte
, you can make address
to be static
member which would guarantee that it will be initialized before first use of a class. You can then reference it in theInstance
initializer:
using System;
using System.Net;
using System.Linq;
public class Program
{
public static void Main()
{
var wants = new WantsByte();
wants.DoSomethingWithHasByte();
}
}
class HasByte
{
public byte[] theByteArray = new byte[4];
public HasByte(IPAddress someAddress)
{
theByteArray = someAddress.GetAddressBytes();
}
}
class WantsByte
{
static IPAddress address = IPAddress.Parse("192.168.1.1");
HasByte theInstance = new HasByte(WantsByte.address);
public void DoSomethingWithHasByte()
{
Console.WriteLine(String.Join(",", theInstance.theByteArray.Select(o => o.ToString()).ToArray()));
}
}
also gives the same output:
192,168,1,1
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments