Getting type from an object in C# - vb.net-to-c#

What is wrong in this code? ..
public void gett(object dato, ref object ty)
{
dato = 1; // <- this compiles
Type t = typeof(dato); //<--- here i Got an error
if (t == typeof(int))
{
ty= 1
}
else
{
ty=""
}
}
I got an error "The type or namespace name 'dato' could not be found (are you missing a using directive or an assembly reference?) "
I want to put this VB .net code into c#
Sub getty(ByVal dato As Object, ByRef ty As Object)
If IsDBNull(dato) Then
Select Case ty.GetType.FullName
Case GetType(Integer).FullName
ty = 0
Case GetType(String).FullName
ty = ""
Case GetType(Guid).FullName
ty = New Guid("00000000-0000-0000-0000-000000000000")
Case GetType(DateTime).FullName
Dim da As DateTime = New DateTime(1900, 1, 1)
ty = da
Case Else
ty = ""
End Select
Else
ty = dato
End If
End Sub
Thanks

The typeof operator only works on types. Try dato.GetType() instead.

To expand upon Mark's answer, dato is not a type, it is a variable. typeof() works on the type (i.e. the class or struct, which in this case is object).
Indeed what you seek is runtime type identification, which you get with dato.GetType().

Related

EMF: Defining a generic containment reference in an Ecore metamodel

It is a long time since I have used EMF and I am stuck on this.
I would like to create a generic type equivalent to:
class Result<T:ASTNode>{
T root;
}
I am defining this in Kotlin:
val result = ePackage.createEClass("Result").apply {
// I think this part is correct
val typeParameter = EcoreFactory.eINSTANCE.createETypeParameter().apply {
this.name = "T"
this.eBounds.add(EcoreFactory.eINSTANCE.createEGenericType().apply {
// astNode is my EClass
this.eClassifier = astNode
})
}
this.eTypeParameters.add(typeParameter)
val rootContainment = EcoreFactory.eINSTANCE.createEReference()
rootContainment.name = "root"
// STUCK!
// here should I set rootContainment.eType? rootContainment.eGenericType?
// how?
rootContainment.isContainment = true
rootContainment.lowerBound = 0
rootContainment.upperBound = 1
this.eStructuralFeatures.add(rootContainment)
addContainment("issues", issue, 0, -1)
}
The equivalent .ecore is :
<eClassifiers xsi:type="ecore:EClass" name="Result">
<eTypeParameters name="T">
<eBounds eClassifier="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
</eTypeParameters>
<eStructuralFeatures xsi:type="ecore:EReference" name="t">
<eGenericType eTypeParameter="#//Result/T"/>
</eStructuralFeatures>
so you want to use rootContainment.eGenericType with a new EGenericType that references your ETypeParameter

why does cocos2d-x version 4.0 not have macro CCARRAY_FOREACH?

I can't find macro CCARRAY_FOREACH but i found CCARRAYDATA_FOREACH. Are those the same ? I mean can i use CCARRAYDATA_FOREACH instead?
And i tried but visual studio gives me an error of expression must have pointer type when i was using CCARRAYDATA_FOREACH and i can't solve. Any help would be appreciated.
Here is part of my code
void BaseManager::update(float dt){
auto visibleSize = Director::getInstance()->getVisibleSize();
Ref* obj = NULL;
Coin* coin = NULL;
int setNum = 0;
CCARRAYDATA_FOREACH(m_coinArr,obj){ // this line produces error: expression must have pointer type
coin = (Coin*)obj;
if(coin->getPositionX() < -coin->getConSize().width/2){
coin->setVisible(false);
}
if( !coin->isVisible() ){
setNum ++;
}
coin->setPositionX(coin->getPositionX()-map_speed);
}
................

a value of type "void *" cannot be assigned to an entity of type "RANDOMSTRUCT *"

So I was working on malloc in void. And I have a code:
int iInitRandomPhaseArrays(WS_ELEMENT *Aufbau, RANDOMSTRUCT **random)
{
WS_ELEMENT *Act;
int iCounter = 0, i;
RANDOMSTRUCT *dummy;
Act = Aufbau;
if (*random != NULL)
return -1;
while (Act != NULL)
{
if (Act->operation == Linsenarray)
iCounter++;
Act = Act->pNext;
}
if (iCounter)
{
dummy = malloc(iCounter * sizeof(random));
ran1_3ARG(&ran1_idum, &ran1_iy, ran1_iv);
dummy[0].idum = ran1_idum;
dummy[0].iy = ran1_iy;
memcpy(dummy[0].iv, ran1_iv, sizeof(ran1_iv));
for (i = 0; i < iCounter; i++)
ran1_3ARG(&dummy[i].idum, &dummy[i].iy, dummy[i].iv);
dummy[0].Anzahl = iCounter;
*random = dummy;
}
return iCounter;
}
here error:
a value of type "void *" cannot be assigned to an entity of type "RANDOMSTRUCT *"
Can anyone help me solve it?
Change the line:
dummy = malloc(iCounter * sizeof(random));
to say:
dummy = (RANDOMSTRUCT *)malloc(iCounter * sizeof(RANDOMSTRUCT));
dummy = malloc(iCounter * sizeof(random));
this allocates the wrong amount of memory (a multiple of a pointer size, not the pointed-to) and returns a void*. In c++ void* doesn't implicitly convert to other pointer types. In c it does.
Assuming you actually mean to use C-isms in C++ code, write this:
template<class T>
T* typed_malloc( std::size_t count = 1 ) {
return static_cast<T*>(malloc( sizeof(T)*count ));
}
this function is a type-safe version of malloc that handles 9999/10000 uses, and prevents an annoying class of bugs.
Then change the line of code to:
dummy = typed_malloc<RANDOMSTRUCT>(iCounter);
Sometimes using malloc in c++ isn't easy to remove, because your code interacts with c code. This kind of change can eliminate bugs before they happen as you modify c code to c++ relatively transparently.

How to get an arrow function's body as a string?

How to get code as string between {} of arrow function ?
var myFn=(arg1,..,argN)=>{
/**
*Want to parse
* ONLY which is between { and }
* of arrow function
*/
};
If it is easy to parse body of simple function : myFn.toString().match(/function[^{]+\{([\s\S]*)\}$/)[1]; is enough . However, Arrow function does not contains function keyword in its definition .
I came looking for a solution because I didn't feel like writing one, but I wasn't sold on the accepted answer. For anyone interested in an ES6 1-liner, I wrote this method, which handles all the cases I needed - both normal functions and arrow functions.
const getFunctionBody = method => method.toString().replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i, '$2$3$4');
This is my attempt:
function getArrowFunctionBody(f) {
const matches = f.toString().match(/^(?:\s*\(?(?:\s*\w*\s*,?\s*)*\)?\s*?=>\s*){?([\s\S]*)}?$/);
if (!matches) {
return null;
}
const firstPass = matches[1];
// Needed because the RegExp doesn't handle the last '}'.
const secondPass =
(firstPass.match(/{/g) || []).length === (firstPass.match(/}/g) || []).length - 1 ?
firstPass.slice(0, firstPass.lastIndexOf('}')) :
firstPass
return secondPass;
}
const K = (x) => (y) => x;
const I = (x) => (x);
const V = (x) => (y) => (z) => z(x)(y);
const f = (a, b) => {
const c = a + b;
return c;
};
const empty = () => { return undefined; };
console.log(getArrowFunctionBody(K));
console.log(getArrowFunctionBody(I));
console.log(getArrowFunctionBody(V));
console.log(getArrowFunctionBody(f));
console.log(getArrowFunctionBody(empty));
It's probably more verbose than it needs to be because I tried to be generous about white space. Also, I'd be glad to hear if anyone knows how to skip the second pass. Finally, I decided not to do any trimming, leaving that to the caller.
Currently only handles simple function parameters. You'll also need a browser that natively supports arrow functions.

How to coerce a xlTypeNum to double in C++ using Excel 2007 SDK

Well I am attempting to make my way through developing an Excel Add-in. I am trying small functions with the sample code in Excel 2007 SDK as as a guide. I am having difficulty with attempting to display a double type data in Excel. Assuming the UDF is called DisplayDouble() when the sample code is executed and a call is placed with an argument of real type data such as DisplayDouble(12.3) the sample code works yet if I attempt to use an argument that references a real type data from cell such as DisplayDouble(A1) where cell A1 in the Excel worksheet has the value 12.3 the sample code does not work
You can see the sample code below this paragraph. Any hints will help me move along the learning ladder
_declspec(dllexport) LPXLOPER12 WINAPI DisplayDouble (LPXLOPER12 n)
{
static XLOPER12 xResult;
XLOPER12 xlt;
int error = -1;
double d;
switch (n->xltype)
{
case xltypeNum:
d = (double)n->val.num;
if (max < 0)
error = xlerrValue;
xResult.xltype = xltypeNum;
xResult.val.num = d;
break;
case xltypeSRef:
error = Excel12f(xlCoerce, &xlt, 2, n, TempNum12(xltypeNum));
if (!error)
{
error = -1;
d = xlt.val.w;
xResult.xltype = xltypeNum;
xResult.val.num = d;
}
Excel12f(xlFree, 0, 1, &xlt);
break;
default:
error = xlerrValue;
break;
}
if ( error != - 1 )
{
xResult.xltype = xltypeErr;
xResult.val.err = error;
}
//Word of caution - returning static XLOPERs/XLOPER12s is not thread safe
//for UDFs declared as thread safe, use alternate memory allocation mechanisms
return(LPXLOPER12) &xResult;
}
looks like you coerced the value to xltypeNum but are then taking the integer value, with d = xlt.val.w rather than d = xlt.val.num