1

Say I have the following declarations:

struct SomeStructure
{
    string Message;
    int StartValue;
    int EndValue;
}

SomeStructure _SomeStructure;

I will never have more than one SomeStructure variable declared so I was wondering if there's a way to combine the two together in a single statement, something like:

struct SomeStructure
{
    string Message;
    int StartValue;
    int EndValue;
} _SomeStructure;

I need to make it explicit that no other variables using the struct are to be declared.

5
  • 4
    No, there is not. Commented Jul 17, 2018 at 9:51
  • If I understand correctly the association of a Message, StartValue and EndValue is a one-shot object ? (=used once in one place) Commented Jul 17, 2018 at 10:01
  • @mjwills how about ValueTuple: (string Message, int StartValue, int EndValue) _SomeStructure; Commented Jul 17, 2018 at 10:09
  • Are you wanting this to be like a singleton? ie if something else tries to create it it returns the single already existing thing? Or do you want to limit it so that only one particular place in the code is able to create or retrieve this item? Commented Jul 17, 2018 at 10:14
  • @Magnus It is about the closest you will get, yes. Which is why I upvoted that option below. Commented Jul 17, 2018 at 10:39

2 Answers 2

4

ValueTuple seems to be the perfect fit for your requirements:

  • Make explicit this is a one-shot value
  • Implemented behind the scene as a struct

var _SomeStructure = (Message: "Hello", StartValue: 1, EndValue: 2);

Or without using var (as requested):

(string Message, int StartValue, int EndValue) _SomeStructure = ("Hello", 1, 2);

Sign up to request clarification or add additional context in comments.

1 Comment

var cannot be used at the module level, hence my problem.
1

You can create anonymous entities like this.

var v = new { Message = "Hello" , StartValue = 1, EndValue = 2}; 

For more details, look at the documentation here:

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/anonymous-types

However, for strict typing, you will need to create a struct or class.

4 Comments

IIRC, anonymous types are implemented as classes, not structs
You are correct, but in practice the anonymous types are so limited, it makes little difference.
It depends on the use case really... if memory location (stack vs heap) or type (value vs reference) are important, it could make quite a large difference. Of course, if neither of those are factors are relevant, anonymous types are fine.
Thanks but that doesn't answer my question. I need to make it explicit that no other variables using the struct are to be declared. I modified the question to make it clear.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.