'Does a struct make sense to return Data from a function in a structured way? (when is a struct apropriate?)

Intro

So far I am trying to wrap my head around structs. I have found many answers on the Topic "When to use a struct". Most of them are vague such as advice against the use of structs in general, with few exceptions. There are explanations of when to use structs (few examples):

  • immutable Data
  • value semantics as opposed to reference semantics
  • need them in code passing structured data to/from C/C++
  • Do not use structs unless you need them

But no example code as to when this case actually happens that it makes sense.

probably one of the most well known Questions/Answers is this one: When should I use a struct rather than a class in C#?

Project structure

class StorageBlock<Type>:

/// this is a storage block. It is not a struct because the data is not immutable and it
/// should be passed by reference
public class StorageBlock<Type>
{
    Type[] Data;
    /* other stuff */
}

methodBlockSearcher():

public (StorageBlock<Type> FoundBlock, int FoundIndex) SearchBlock(Type searchForThisElement)
{
    StorageBlock<Type> found = Blocks.Find(searchForThisElement);
    int index = Array.IndexOf(found.Data, searchForThisElement);
    return (found,index);
} 

caller example:

(StorageBlock<Type> FoundBlock, int FoundIndex) searchResult = SearchBlock(searchElement);
/* process SearchResult(s) */

Questions

I wonder if it makes sense to convert (StorageBlock<Type> FoundBlock, int FoundIndex) searchResult to a struct. The search result should be immutable. It is only there to provide a return from specific indexing operations.

something like this:

struct BlockIndex
{
    StorageBlock<Type> Block;
    int Index;
}

Because a struct is a DataType, not a reference type, I also wonder if BlockIndex.Block (which is a class) will be a reference to the instance of block or a copy of the found block.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source